python使用paramiko模块实现ssh登录执行命令
2017-04-10 16:49
891 查看
python ssh登录,使用paramiko模块
在实际使用中,往往是禁止root进行登录,因此需要进行用户切换。
在实际使用中,往往是禁止root进行登录,因此需要进行用户切换。
#coding=utf8 import paramiko import time import logging ''' if user root,can not login,must use user xx and then switch to root not root ,then run ''' def _conn_root(ip,port,username,passwd,cmd): s = paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: #此处写入一个用于登录的用户 s.connect(hostname=ip, port=int(port), username='xx', password='xx') except: logging.info('err: can not conn %s ,pls check %s and password of xx',(ip,ip)) if username == 'root' or 'xx': ssh = s.invoke_shell() time.sleep(1) if username=='xx': ssh.send('su - xx\n') else: ssh.send('su -\n') buff = '' while not buff.endswith('Password: '): resp = ssh.recv(2048) buff += resp ssh.send(passwd) ssh.send('\n') buff = '' while not buff.endswith('# '): resp = ssh.recv(2048) buff += resp ssh.send(cmd) ssh.send('\n') buff = '' time.sleep(1) resp = ssh.recv(2048) resp = '' while not buff.endswith('# '): resp = ssh.recv(2048) print resp buff += resp s.close() result = buff else: stdin, stdout, stderr = s.exec_command(cmd) result = stdout.read() s.close() return result def _conn_nomal(ip,port,username,passwd,cmd): s = paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: s.connect(hostname=host, port=int(port), username=username, password=password) except: logging.info('err: can not connect %s ,pls check %s and user && password',(ip,ip)) #'get result' stdin, stdout, stderr = s.exec_command(cmd) result = stdout.read() s.close() return result def Connect(ip,port=22,username='xx',passwd='xx',cmd='echo '): if username=='root' or 'xx': return _conn_root(ip,port,username,passwd,cmd) else: return _conn_nomal(ip,port,username,passwd,cmd)
相关文章推荐
- python使用paramiko模块实现ssh远程命令执行,与sftp文件下载功能
- Python实现ssh登录执行shell命令并将结果写入mysql数据库
- ssh批量登录并执行命令的python实现代码
- linux使用Python上秘钥远程登录ssh执行shell命令
- Python 使用paramiko实现远程登录Linux主机并执行命令和操作
- ssh批量登录并执行命令(python实现)
- ssh批量登录并执行命令(python实现)
- ssh批量登录并执行命令的python实现代码
- ssh批量登录并执行命令(python实现)
- python使用paramiko模块实现ssh远程登陆上传文件并执行
- ssh批量登录并执行命令的python实现代码
- python 使用ssh远程登录并执行命令返回结果
- python使用paramiko模块实现ssh远程登陆上传文件并执行
- ssh批量登录并执行命令(python实现)
- Python实现ssh批量登录并执行命令
- Windows使用SSH Secure Shell实现免密码登录Linux的方法以及使用scp2命令免密码下载文件
- Python实现ssh批量登录并执行命令【转】
- Python实现ssh批量登录并执行命令
- python下paramiko模块学习之一:ssh登录和执行命令