概述

最近在部分项目上需要用到python登陆ssh的方法,作为一个小白,对该登陆方法一进行一个实践。

实践

代码

import paramiko

ssh = paramiko.SSHClient()


def ssh_login(ip, port, username, password):
    global ssh
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, username, password)
    return


def ssh_exe_cmd(cmd):
    global ssh
    stdin, stdout, stderr = ssh.exec_command(cmd)
    str1 = stdout.read().decode('utf-8')
    print(str1)
    return


def main():
    host = '10.126.38.110'
    port = '22'
    username = 'root'
    password = 'YOURPASS'
    ssh_login(host, port, username, password)
    print('已经登录到主机: '+host)
    print('系统内核版本:')
    ssh_exe_cmd('uname -ar')
    print('系统当前时间:')
    ssh_exe_cmd('date')
    ssh.close()
    return


main()

以上代码是一个举例,可以基于此种进行拓展。

效果

image.png

以上是其中一种方法,后续进行更新另外一种。