在Paramiko中执行多个命令,使命令受其前任影响 [英] Execute multiple commands in Paramiko so that commands are affected by their predecessors
问题描述
我正在慢慢尝试为 SSH 和 FTP 制作一个 python 脚本来做一些我必须一直做的手动文件.我正在使用 Paramiko 并且会话似乎命令,并打印目录但我的更改目录命令似乎不起作用,它打印了我在
I am slowly trying to make a python script to SSH then FTP to do some manual file getting I have to do all the time. I am using Paramiko and the session seems to command, and prints the directory but my change directory command doesn't seem to work, it prints the directory I start in
/01/home/
import paramiko
hostname = ''
port = 22
username = ''
password = ''
#selecting PROD instance, changing to data directory, checking directory
command = {
1:'ORACLE_SID=PROD',2:'cd /01/application/dataload',3:'pwd'
}
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname,port,username,password)
for key,value in command.items():
stdin,stdout,stderr=ssh.exec_command(value)
outlines=stdout.readlines()
result=''.join(outlines)
print (result)
ssh.close()
推荐答案
当您多次运行 exec_command
时,每个命令都会在其自己的shell"中执行.所以前面的命令对后面命令的环境没有影响.
When you run exec_command
multiple times, each command is executed in its own "shell". So the previous commands have no effect on an environment of the following commands.
如果您需要前面的命令来影响以下命令,只需使用服务器 shell 的适当语法.大多数 *nix shell 使用分号或双与号(具有不同的语义)来指定命令列表.在您的情况下,与号更合适,因为它仅在先前的命令成功时才执行以下命令:
If you need the previous commands to affect the following commands, just use an appropriate syntax of your server shell. Most *nix shells use a semicolon or an double-ampersand (with different semantics) to specify a list of commands. In your case, the ampersand is more appropriate, as it executes following commands, only if previous commands succeed:
command = "ORACLE_SID=PROD && cd /01/application/dataload && pwd"
stdin,stdout,stderr = ssh.exec_command(command)
在很多情况下,您甚至不需要使用多个命令.
In many cases, you do not even need to use multiple commands.
例如,您可以在交互式使用 shell 时执行以下操作,而不是此序列:
For example, instead of this sequence, that you might do when using shell interactively:
cd /path
ls
你可以这样做:
ls /path
另见:如何使用Paramiko exec_command获取每个依赖的命令执行输出
这篇关于在Paramiko中执行多个命令,使命令受其前任影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!