无法导航到远程 Linux 机器上的所需文件夹,我该如何使用 paramiko 做到这一点?

Not able to navigate to desired folder on remote Linux machine, how do i do that using paramiko?

我正在使用 Python paramiko 和 我的网站服务器有这样的文件夹结构-

1]dir1
      --dirP
      --dirQ
2]dir2
      --dirA
          --file.sh
      --dirB
3]dir3

我想从 dir2 文件夹中的 dirA 访问 file.sh 的位置

我试过了-

import paramiko
client.connect('mysite.com', username='something', password='something')
stdin, stdout, stderr = client.exec_command('cd dir2')
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
    print('... ' + line.strip('\n'))

但我得到输出-

  ...dir1
  ...dir2
  ...dir3

预期输出是-

...dirA
...dirB

并建议我如何也执行 file.sh?

client.exec_command("cmd ...") 就像命令 ssh user@host "cmd ..." 所以

client.exec_command('cd dir2')
client.exec_command('ls')

就像

ssh user@host 'cd dir2' # this would not affect the following `ls'
ssh user@host 'ls'

。所以你需要这样做:

client.exec_command('cd dir2; ls')

这就像

ssh user@host 'cd dir2; ls'

或者如果你使用变量需要加上+ 例如

client.exec_command('str(var1)+str(var2))