import paramiko import sys,os host_list=[ #主机名,ip [‘app176‘,‘192.168.100.1‘,], ] def hostname(): s = paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) for host in host_list: print(host[0],host[1]) s.connect(host[1],22,‘root‘,‘#‘,timeout=5) stdin,stdout,stderr=s.exec_command(‘hostname {}‘.format(host[0])) cmd_result = stdout.read(),stderr.read() for line in cmd_result: print(line) s.close() def network(): s = paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #忽略第一次登陆时的konwn_hosts检测 for host in host_list: print(host[0],host[1]) s.connect(host[1],22,‘root‘,‘#‘,timeout=5) #认证 分别为主机地址,端口号,用户,密码,超时时间 stdin,stdout,stderr=s.exec_command(‘hostname‘) #获取原主机名 h = stdout.read().decode().strip() for line in h: stdin,stdout,stderr=s.exec_command("sed -i ‘s/{0}/{1}/‘ /etc/sysconfig/network".format(h,host[0]))#执行命令 cmd_result = stdout.read(),stderr.read() print(cmd_result) def hosts(): s = paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) for host in host_list: print(host[0],host[1]) s.connect(host[1],22,‘root‘,‘#‘,timeout=5) stdin,stdout,stderr=s.exec_command(‘hostname‘) h = stdout.read().decode().strip() for line in h: stdin,stdout,stderr=s.exec_command("sed -i ‘s/{0}/{1}/‘ /etc/hosts".format(h,host[0])) cmd_result = stdout.read(),stderr.read() if __name__ == ‘__main__‘: hosts() network() hostname()
时间: 2024-10-23 07:09:24