公司有部分服务器root密码被禁用,有部分没有禁用,禁用root的服务器需要通过tomcat用户登陆系统,切换至root修改端口,没有禁用的直接修改root密码;
#-*- coding:utf-8 -*- import paramiko import time '''远程登录修改端口''' def ssh_connect( _host, _username, _password ): try: _ssh_fd = paramiko.SSHClient() _ssh_fd.set_missing_host_key_policy( paramiko.AutoAddPolicy() ) _ssh_fd.connect( _host, username = _username, password = _password ) except Exception as e: return ('ssh %s@%s: %s' % (_username, _host, e)) return _ssh_fd def ssh_exec_cmd( _ssh_fd, _cmd ): return _ssh_fd.exec_command( _cmd ) def remote_ssh(_ssh_fd,cmd,root_pwd): ssh = _ssh_fd.invoke_shell() time.sleep(0.1) ssh.send('su - ') buff = '' while not buff.endswith('Password: '): resp = ssh.recv(9999) buff +=resp ssh.send(root_pwd) ssh.send(' ') buff = '' while not buff.endswith('# '): resp = ssh.recv(9999) buff +=resp ssh.send(cmd) ssh.send(' ') buff = '' while not buff.endswith('# '): resp = ssh.recv(9999) buff +=resp _ssh_fd.close() result = buff return result def ssh_close( _ssh_fd ): _ssh_fd.close() def main(): hostname = ['xxx.xx.xx.xx'] username = ['root','tomcat'] password = ['********','*********'] cmd = 'echo "Port 61822" >> /etc/ssh/sshd_config && service sshd restart' for i in range(len(hostname)): sshd = ssh_connect( hostname[i] , username[0] , password[0]) if "Authentication failed" in str(sshd): print 'PermitRootLogin no' sshd = ssh_connect( hostname[i] , username[1] , password[1]) print remote_ssh(sshd,cmd,password[0]) else: print 'PermitRootLogin yes' stdin, stdout, stderr = ssh_exec_cmd( sshd, cmd ) stdout_list = stdout.readlines() print stdout_list if __name__ == "__main__": # pass main()