You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
import paramiko
|
|
|
|
|
|
|
|
|
|
'''
|
|
|
|
|
思路:使用paramiko工具连接服务器,并将执行命令的结果返回给程序,这里我们使用了sshclient方法\
|
|
|
|
|
首先定义类,构造函数中传入了需要用到的属性 账号信息,定义op方法实现执行命令功能。
|
|
|
|
|
'''
|
|
|
|
|
class sshd():
|
|
|
|
|
def __init__(self,hostname,passwd,port=22,username='root'): # 定义函数传入连接远程用到的属性
|
|
|
|
|
self.ssh = paramiko.SSHClient() # 调用sshclient方法
|
|
|
|
|
self.hostname=hostname # 转换属性
|
|
|
|
|
self.port = port
|
|
|
|
|
self.username = username
|
|
|
|
|
self.passwd = passwd
|
|
|
|
|
def op(self,cmd):
|
|
|
|
|
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts里的主机
|
|
|
|
|
self.ssh.connect(hostname=self.hostname,
|
|
|
|
|
port=self.port,
|
|
|
|
|
username=self.username,
|
|
|
|
|
password=self.passwd)
|
|
|
|
|
stdin, stdout, stderr = self.ssh.exec_command(cmd)
|
|
|
|
|
self.stdin = stdin
|
|
|
|
|
self.stdout= str(stdout.read(),encoding='utf-8') #将结果返回并解码
|
|
|
|
|
self.stderr= str(stderr.read(),encoding='utf-8')
|
|
|
|
|
self.ssh.close()
|
|
|
|
|
if self.stdout:
|
|
|
|
|
return self.stdout
|
|
|
|
|
else:
|
|
|
|
|
return self.stderr
|
|
|
|
|
def __str__(self):
|
|
|
|
|
return 'QianFeng cloud computing testing'
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
aa = sshd(hostname='172.16.147.151',passwd='1')
|
|
|
|
|
s = aa.op('ls /root')
|
|
|
|
|
print(s,end="")
|