[toc]
python自动化之admin自动切换root
ssh登录系统,如果是非root帐号(普通帐号)登录采取行动,则su切换到root
#!/usr/env/bin python # -*- coding:utf-8 -*- # des:ssh登录系统,如果是非root帐号(普通帐号)登录采取行动,则su切换到root # python 的SSHV2 protocol协议实现,用于python调用各种ssh功能; import paramiko # python内置时间模块 import time #根据用户名密码从普通用户揽权到root用记执行给定命令 def ssh_su_root(ip,username,password,root_pwd,cmd): #建立SSHClient对象 myssh = paramiko.SSHClient() #设置自动接收公钥 myssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: #使用给定用户名密码尝试连接服务器 myssh.connect(ip, 22, username=username, password=password, timeout=4) except Exception, ex: print str(ex) return # 如果默认root不允许远程登录,提供的是普通用户帐号+root帐号, #则调用invoke_shell,使用交互式shell方式切换同到root帐号,并执行命令。 if username != 'root': print "I am NOT root" ssh = myssh.invoke_shell() time.sleep(0.2) ssh.send('su -\n') buff = '' #循环检测密码输入提示,出现后发送root口令, while not (buff.endswith('Password:') or buff.endswith('密码: ')): #从接收缓存中读入最多9999bytes数据。 resp = ssh.recv(9999) buff += resp ssh.send(root_pwd) ssh.send('\n') buff = '' #循环检测#提示符,出现后执行传入的命令。 while not buff.endwith('# '): resp = ssh.recv(9999) buff += resp ssh.send[cmd] ssh.send('\n') buff ='' #循环检测#提示符,意味着命令执行完成,出现后关闭ssh连接并输出结果。 while not buff.endswith('# '): resp = ssh.recv(9999) buff += resp myssh.close() result = buff print "su root result --->",result myssh.close() else: #如果提供的是root帐号,则直接调用paramiko exec_command 方法,执行命令。 print "I am root" stdin, stdout, stderr = myssh.exec_command(cmd) stdin,write("Y") print "stdout.readlines() --->", stdout.readlines() myssh.close() if __name__ == "__main__": cmd = 'date' ip = 'xx.xxx.xx.xxx' username = 'admin' password = 'xxxxxxxxxx' ssh_su_root(ip, username, password, 'xxxxxxxxxxxx', cmd) username = 'root' ssh_su_root(ip, username, password, 'xxxxxxxxxxxx', cmd)