使用 ssh 连接到远程主机后执行 unix 操作

Perform unix operations after connecting to remote host using ssh

使用 paramiko 连接到远程主机。我如何跨目录移动并执行 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 命令等操作?

这样(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()