ssh/login to a buildserver on the network and logo

2019-08-09 17:21发布

问题:

I am trying to ssh into a buildserver on the network and run some commands and logout of the server,i have looked at other posts and written the following code but its not working?can anyone suggest what is wrong or is there a better way to accomplish this?thanks in advance

import os
import sys
import pexpect
#os.system(ssh username@buildservername)
child = pexpect.spawn('ssh username@buildservername', logfile=sys.stdout)
#child.expect('Are you sure you want to continue connecting (yes/no)?')
#child.sendline('yes')
#child.expect('password:')
child.sendline('password')
cmd = 'hostname'
os.system(cmd)
os.chdir('//local/mnt/workspace')
os.mkdir('newdir')
os.getcwd()

回答1:

You may take a look a the Paramiko library, especialy the SFTPClient

It's a native Python SSHv2 protocol library.

import paramiko

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect('buildservername', username='yadomi', password='password')

sftp = ssh.open_sftp()
sftp.chdir('/local/mnt/workspace')
sftp.mkdir('newdir')