python -ssh学习

def exe_sshcmd(ip,username,userpswd,port,cmd):
    """
    功能:SSH登录到指定设备,并执行对应的命令
    入参:前四项为ssh登录shell的ip和port,具备管理员权限的用户名和密码,
          cmd可以是单条命令,也可以是命令列表
    返回:每次命令执行结果列表,标准输出结果,不包含错误输出

    Examples:
    |Exe Sshcmd| ip|name|pswd|cmd|

    """
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(ip, int(port), username, userpswd)
        ret=[]

        if isinstance(cmd, list):
            cmd = ";".join(cmd)
        print('exe command:',cmd)
        stdin, stdout, stderr=ssh_client.exec_command("%s"%cmd,timeout=30)
        ret=stdout.read()
        retcode = stdout.channel.recv_exit_status()
        print('exe command return info:\n',str(ret,encoding="gbk"))
        print('exe command return code:',stdout.channel.recv_exit_status())
        if stdout.channel.recv_exit_status()!=0:
            print('stderr:',str(stderr.read(),encoding='gbk'))
        ssh_client.close()
        return bytes.decode(ret).strip(),retcode
    except Exception as err:
        print(err)
        print("ssh connect failed(ip=%s,user=%s,pwd=%s,port=%d)." %(ip,username,userpswd,int(port)))
        return "ssh connect fail",1

你可能感兴趣的:(python)