Not able to navigate to desired folder on remote L

2019-01-29 09:09发布

问题:

I am Using Pyhton paramiko and My website server has folder structure like this-

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

where i want to access file.sh from dirA inside dir2 folder

I tried this-

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'))

but i get output-

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

expected output is-

...dirA
...dirB

and also suggest how can i execute file.sh too?

回答1:

client.exec_command("cmd ...") is just like the command ssh user@host "cmd ..." so

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

are just like

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

. So you need to do like this:

client.exec_command('cd dir2; ls')

which is just like

ssh user@host 'cd dir2; ls'


回答2:

Or if you use variables need to add + for example

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