paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作
SSHClient
用于远程连接机器执行基本命令,也可以执行shell脚本
基于用户名密码连接:
def ssh_connect(host_name,user_name,pass_word,exec_cmd): flag = True try: #创建ssh对象 ssh_machine = paramiko.SSHClient() #允许连接不在know_hosts文件中的主机 ssh_machine.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #输入主机名、端口号、用户名、密码连接主机 ssh_machine.connect(hostname=host_name,port=22,username=user_name,password=pass_word) #远程机器执行命令 stdin,stdout,stderr = ssh_machine.exec_command(exec_cmd) #获取命令结果 reslut = stdout reslut_list = reslut.read().split("\n") for reslut in reslut_list: print(reslut) except: flag = False print("连接%s出现异常"%(host_name)) finally: ssh_machine.close() return flag if __name__ == "__main__": host_name = 'root' user_name = 'xxx' pass_word = 'xxx' #shell 脚本 exec_hasno_cmd = ''' 脚本内容 ''' flag = ssh_connect(host_name,user_name,pass_word,exec_hasno_cmd) #判断是否登录成功 if flag: print("\033[32m%s登录成功\033[0m"%(host_name)) else: print("\033[32m%s登录失败\033[0m"%(host_name))