ssh登录服务器并执行命令
#使用password方式登录服务器
import paramiko
hostname = '192.168.1.1'
username = 'root'
password = '123456'
command = 'ip a'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname,username=username,password=password)
stdin,stdout,stderr = ssh.exec_command(command)
print stdout.readlines()
ssh.close()
#使用key方式登录import paramikohostname = '192.168.1.1'username = 'root'port = 22command = 'ip a'ssh = paramiko.SSHClient()ssh.load_system_host_keys()privatekey = os.path.expanduser('id_rsa')key = paramiko.RSAKey.from_private_key_file(privatekey)ssh.connect(hostname=hostname,username=username,pkey=key)stdin,stdout,stderr = ssh.exec_command(command)print stdout.readlines()ssh.close()
#上传单个文件
sftp = paramiko.Transport((hostname,port))sftp.connect(username=username,password=password)sftpssh = paramiko.SFTPClient.from_transport(sftp)localpath = '/usr/local/src/filename'remotepath = '/usr/local/src/filename'sftpssh.put(srcfilename,uploadfilename)sftp.close()
#上传目录下的多个文件sftp = paramiko.Transport((hostname,port))sftp.connect(username=username,password=password)sftpssh = paramiko.SFTPClient.from_transport(sftp)localpath = '/usr/local/src'remotepath = '/usr/local/src'for file in os.listdir(localpath): srcfilename = os.path.join(localpath,file) uploadfilename = os.path.join(remotepath,file) sftpssh.put(srcfilename,uploadfilename)sftp.close()
#下载远程服务器上的目录下的多个文件command = 'cd /usr/local/src && ls'ssh = paramiko.SSHClient()ssh.set_missing_key_host_policy(paramiko.AutoAddPolicy())ssh.connect(hostname=hostname,username=username,password=password)stdin,stdout,stderr = ssh.exec_command(commnad)files = stdout.readlines()sftp = paramiko.Transport((hostname,port))sftp.connect(username=username,password=password)sftpssh = paramiko.SFTPClient.from_transport(sftp)for file in files: file = file.strip('\n') filename= os.path.join(localpath,file) downloadfilename= os.path.join(remotepath,file) sftpssh.get(downloadfilename,filename)sftp.close()