import time
import paramiko
class MySSH(object):
def __init__(self):
self.username="root"
self.password="pwd"
self.ip="127.0.0.1"
self.connect_()
def connect_(self):
try:
self.tran = paramiko.Transport((self.ip,22))#建立一个socket通道
self.ssh = paramiko.SSHClient()
self.tran.start_client() #启动一个客户端
self.tran.auth_password(username=self.username, password=self.password)#用户名和密码登录
self.ssh._transport = self.tran
self.channel = self.tran.open_session()#打开一个会话通道
self.channel.get_pty()#获取终端
self.channel.invoke_shell()#激活终端
print("连接成功")
except paramiko.ssh_exception.SSHException:
print('连接错误')
return None
def disconnect(self):
self.channel.close()
self.tran.close()
def out(self, stdout):
for line in stdout.readlines():
print(line)
print("===========")
def exec(self, cmd):
stdin, stdout, stderr = self.ssh.exec_command(cmd)
self.out(stdout)
def exec_ch(self, cmd):
self.channel.send((cmd+"\n").encode("utf-8"))
def recive_ch(self):
print(self.channel.recv(65535).decode("utf-8"))
print("==========================")
def main(self):
self.exec_ch("pwd")
self.recive_ch()
self.exec_ch("cd /")
self.exec_ch("pwd")
time.sleep(2)
self.recive_ch()
self.disconnect()
if __name__ == '__main__':
MySSH().main()