编程语言
首页 > 编程语言> > 利用Python第三方模块paramiko实现客户端管理工具

利用Python第三方模块paramiko实现客户端管理工具

作者:互联网

import paramiko
import optparse
import sys


def get_params():
    parser = optparse.OptionParser('Usage: <Program> -t target  -u username -p password')
    parser.add_option('-t', '--target', dest='target', type="string", help="Specify IP address of target")    
    parser.add_option('-u', '--username', dest='username', type='string', help='Specify username to login SSH server')
    parser.add_option('-p', '--password', dest='password', type='string', help='Specify password to login SSH server')
    options, args = parser.parse_args()
    if options.target is None or options.username is None or options.password is None:
        print(parser.usage)
        sys.exit(0)
    return options.target, options.username, options.password


class SSHClient:
    def __init__(self, server_ip, username, password) -> None:
        try:
            self.server_ip = server_ip
            self.username = username
            self.password = password
            self.ssh_client = paramiko.SSHClient()
            self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh_client.connect(hostname=self.server_ip, username=self.username, password=self.password)
        except paramiko.AuthenticationException:
            print("Failed to authenticate the SSH server")
            sys.exit(0)
        except:
            print("Failed to connect the SSH server")
            sys.exit(0)

    
    def run(self):
        while True:
            command = input("#~ ")
            if command == 'q':
                break
            stdin, stdout,stderr = self.ssh_client.exec_command(command)
            if stdout:
                res = stdout.read().decode('utf-8')
                print(res)
            if stderr:
                err_res = stderr.read().decode('utf-8')
                print(err_res)
        self.ssh_client.close()


def banner():
    banner = """
        ******************************************************************
        ******************************************************************

                          SSH Client by Jason Wong V1.0

        ******************************************************************
        ******************************************************************
    """
    print(banner)

if __name__ == '__main__':
    banner()
    ssh_server_ip, username, password = get_params()
    ssh_client = SSHClient(ssh_server_ip, username, password)
    ssh_client.run()

运行效果图:

 

标签:username,Python,self,管理工具,server,ssh,password,options,paramiko
来源: https://www.cnblogs.com/jason-huawen/p/16213499.html