我发布了上述有关使用Paramiko收到的持久性错误消息的问题.我不认为这与我的下一个问题有关,但可能是.
我可以使用Paramiko通过SSH成功连接到我的服务器.我可以执行像ls或pwd这样的命令.我似乎无法做的是更改目录.我可以发送命令"cd ..",但是当我跟进"pwd"时,它表明我没有更改目录.它只列出了我登录时的初始目录.
>>> stdin, stdout, stderr = myssh.exec_command("pwd")
>>> stdout.readlines()
['/big/dom/home/myid\n']
>>> stdin, stdout, stderr = myssh.exec_command("cd ../")
>>> stdout.readlines()
[]
>>> stdin, stdout, stderr = myssh.exec_command("pwd")
>>> stdout.readlines()
['/big/dom/home/myid\n']
>>>
Run Code Online (Sandbox Code Playgroud)
我误解了这里发生了什么吗?我应该无法更改目录吗?或者如果我可以,我应该以除了使用exec_command之外的其他方式来做这件事吗?
-
再过7个小时我无法回答我自己的问题,所以答案是:
这个家伙弄清楚了:http://www.vertigrated.com/blog/2010/02/python-remote-ssh-with-paramiko/
您只需使用一个exec_command发送多个命令,例如:
myssh.exec_command('cd ..; pwd')
然后stdout.readlines()将返回您更改的目录.
我想编写一个程序(在Windows 7上的Python 3.x中),它通过ssh在远程shell上执行多个命令.在查看了paramikos的exec_command()函数之后,我意识到它不适合我的用例(因为在执行命令后通道被关闭),因为命令依赖于环境变量(由先前的命令设置)而不能连接到一个exec_command()调用,因为它们将在程序中的不同时间执行.
因此,我想在同一个通道中执行命令.我研究的下一个选项是使用paramikos的invoke_shell()函数实现交互式shell:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=psw, port=22)
channel = ssh.invoke_shell()
out = channel.recv(9999)
channel.send('cd mivne_final\n')
channel.send('ls\n')
while not channel.recv_ready():
time.sleep(3)
out = channel.recv(9999)
print(out.decode("ascii"))
channel.send('cd ..\n')
channel.send('cd or_fail\n')
channel.send('ls\n')
while not channel.recv_ready():
time.sleep(3)
out = channel.recv(9999)
print(out.decode("ascii"))
channel.send('cd ..\n')
channel.send('cd simulator\n')
channel.send('ls\n')
while not channel.recv_ready():
time.sleep(3)
out = channel.recv(9999)
print(out.decode("ascii"))
ssh.close()
Run Code Online (Sandbox Code Playgroud)
这段代码存在一些问题:
我对这种"非决定论"感到困惑,非常感谢你的帮助.
我有一个创建连接的类。我可以在通道关闭之前连接并执行 1 个命令。在另一个系统上,我可以执行多个命令并且通道不会关闭。显然,这是我尝试连接的系统的配置问题。
class connect:
newconnection = ''
def __init__(self,username,password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect('somehost', username=username,password=password,port=2222,timeout=5)
except:
print "Count not connect"
sys.exit()
self.newconnection = ssh
def con(self):
return self.newconnection
Run Code Online (Sandbox Code Playgroud)
然后我使用'ls'命令只是为了打印一些输出
sshconnection = connect('someuser','somepassword').con()
stdin, stdout, stderr = sshconnection.exec_command("ls -lsa")
print stdout.readlines()
print stdout
stdin, stdout, stderr = sshconnection.exec_command("ls -lsa")
print stdout.readlines()
print stdout
sshconnection.close()
sys.exit()
Run Code Online (Sandbox Code Playgroud)
在第一个 exec_command 运行后,它会打印目录列表的预期输出。当我在第一个 exec_command 之后打印 stdout 时,看起来通道已关闭
<paramiko.ChannelFile from <paramiko.Channel 1 (closed) -> <paramiko.Transport at 0x2400f10L (cipher aes128-ctr, 128 bits) (active; 0 open channel(s))>>> …Run Code Online (Sandbox Code Playgroud)