2017-08-29 68 views
0

使用paramiko连接到远程主机。我如何移动目录并执行unix操作?下面使用ssh连接到远程主机后执行unix操作

import paramiko 
ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('remote ip', username='username', password='password') 
ftp = ssh.open_sftp() 
ssh.exec_command('cd /folder1/folder2') 

示例代码如何执行就像一个目录列表文件,检查当前的工作目录并执行其他的Unix命令操作?

回答

1

这样(在ls命令为例):

import paramiko 
import sys 

ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('x.x.x.x', port=22, username='user', password='pass') 
stdin, stdout, stderr = ssh.exec_command('ls') 

# Wait for the command to terminate 
while not stdout.channel.exit_status_ready(): 
    # Only print data if there is data to read in the channel 
    if stdout.channel.recv_ready(): 
     rl, wl, xl = select.select([stdout.channel], [], [], 0.0) 
     if len(rl) > 0: 
      # Print data from stdout 
      print stdout.channel.recv(1024), 



ssh.close() 
+0

我想这一点,但是当我的stdout打印不会列出目录中的所有文件。我从>> – Harikrishna

+0

不知道。它在这里起作用。看看这个Paramiko文档(命令SSHClient):http://docs.paramiko.org/en/2.2/api/client.html –

+0

我编辑了我的代码,添加一个等待循环stdout在打印之前终止。 –

相关问题