在 Paramiko 的 SFTP 路径中使用环境变量
Use environment variable in SFTP path in Paramiko
我在我的服务器上 运行 脚本并试图从我的防火墙获取一些文件。使用环境变量($
符号)引用文件时出现 "file not found" 错误。 B、但是进入正常路径就可以拿到我的文件了。我知道代码看起来不太好,这只是一个简单的例子。这是我的工作代码:
_savedLocation = "/home/kartal/Desktop/aaa.tgz"
folder, savedLocation = os.path.split(_savedLocation)
remotepath = "$FWDIR/bin/upgrade_tools/"
remotefile = remotepath + savedLocation
stdin, stdout, stderr =
ssh.exec_command("cd {} && yes | ./migrate export {} ".format(remotepath, savedLocation))
time.sleep(120)
command = "cd {} && chmod 777 {}".format(remotepath, savedLocation)
stdin, stdout, stderr = ssh.exec_command(command)
sftp = ssh.open_sftp()
sftp.get(remotefile, _savedLocation)
sftp.close()
ssh.close()
如果我使用真实路径作为 remotepath = "/opt/r80/fw1/bin/upgrade_tools/"
,代码有效。
顺便说一句,我 运行 "migrate" 脚本的第一步是 $FWDIR
。所以 $FWDIR
适用于 exec_command
,但不适用于 SFTP get
。
我哪里做错了,我该怎么办?
您不能在 SFTP 中使用环境变量。您必须使用真实路径。在这种情况下,实际路径是 /opt/CPsuite-R80/fw1
.
如果真实路径不固定,确实需要从变量值中获取真实路径,则需要使用不同的接口解析变量值(例如使用shell访问) .然后在 SFTP 中使用解析值。这就是您在 WinSCP 中所做的——您在 shell 中执行 cd $FWDIR
。 shell 将 $FWDIR
解析为 /opt/CPsuite-R80/fw1
。在Paramiko中,可以使用SSHClient.exec_command
解析变量:
stdin, stdout, stderr = ssh.exec_command("echo $FWDIR")
fwdir = stdin.read()
我在我的服务器上 运行 脚本并试图从我的防火墙获取一些文件。使用环境变量($
符号)引用文件时出现 "file not found" 错误。 B、但是进入正常路径就可以拿到我的文件了。我知道代码看起来不太好,这只是一个简单的例子。这是我的工作代码:
_savedLocation = "/home/kartal/Desktop/aaa.tgz"
folder, savedLocation = os.path.split(_savedLocation)
remotepath = "$FWDIR/bin/upgrade_tools/"
remotefile = remotepath + savedLocation
stdin, stdout, stderr =
ssh.exec_command("cd {} && yes | ./migrate export {} ".format(remotepath, savedLocation))
time.sleep(120)
command = "cd {} && chmod 777 {}".format(remotepath, savedLocation)
stdin, stdout, stderr = ssh.exec_command(command)
sftp = ssh.open_sftp()
sftp.get(remotefile, _savedLocation)
sftp.close()
ssh.close()
如果我使用真实路径作为 remotepath = "/opt/r80/fw1/bin/upgrade_tools/"
,代码有效。
顺便说一句,我 运行 "migrate" 脚本的第一步是 $FWDIR
。所以 $FWDIR
适用于 exec_command
,但不适用于 SFTP get
。
我哪里做错了,我该怎么办?
您不能在 SFTP 中使用环境变量。您必须使用真实路径。在这种情况下,实际路径是 /opt/CPsuite-R80/fw1
.
如果真实路径不固定,确实需要从变量值中获取真实路径,则需要使用不同的接口解析变量值(例如使用shell访问) .然后在 SFTP 中使用解析值。这就是您在 WinSCP 中所做的——您在 shell 中执行 cd $FWDIR
。 shell 将 $FWDIR
解析为 /opt/CPsuite-R80/fw1
。在Paramiko中,可以使用SSHClient.exec_command
解析变量:
stdin, stdout, stderr = ssh.exec_command("echo $FWDIR")
fwdir = stdin.read()