python通过ssh连接服务器,详细教程,直接上代码

# coding:utf-8
import paramiko

class LinuxOrder():

    def __init__(self, ip, port, username, password, timeout):
        '''
        :param ip: 服务器IP
        :param port: ssh 连接的端口
        :param username: 服务器用户名
        :param password: 服务器密码
        :param timeout: 连接超时时间
        '''
        try:
            self.ip = ip
            self.port = port
            self.username = username
            self.password = password
            self.timeout = timeout
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(self.ip, self.port, self.username, self.password, timeout=self.timeout)
            print('{0}:连接成功'.format(self.ip))
        except Exception as e:
            print('{0}:连接失败'.format(self.ip))
            raise e

    def run(self):
        '''执行代码'''
        cmd = '这里是linux命令'
        self.ssh.exec_command(cmd)

    def close_ssh(self):
        '''关闭ssh连接'''
        self.ssh.close()
        print('关闭ssh连接')


if __name__ == '__main__':
    L = LinuxOrder('ip', '端口', '用户名', '密码', '超时时间')

你可能感兴趣的:(python工具脚本)