from sh import ssh
PASS = 'xxxx'
def ssh_interact(line, stdin):
line = line.strip()
print(line)
if line.endswith('password:'):
stdin.put(PASS)
ssh('x.x.x.x', _out=ssh_interact)
# coding: utf-8 import os.path from paramiko import SSHClient, AutoAddPolicy, AuthenticationException class ConnectError(Exception): """ 连接错误时抛出的异常 """ pass class RemoteExecError(Exception): """ 远程执行命令,失败时抛出的异常 """ pass class SCPError(Exception): """ 远程下发文件时抛出的异常 """ pass
...
class Remote(object):
def __init__(self, host, username, password=None, port=22, key_filename=None):
self.host = host
self.username = username
self.password = password
self.port = port
self.key_filename = key_filename
self._ssh = None
def _connect(self):
self._ssh = SSHClient()
self._ssh.set_missing_host_key_policy(AutoAddPolicy())
try:
if self.key_filename:
self._ssh.connect(self.host, username=self.username, port=self.port, key_filename=self.key_filename)
else:
self._ssh.connect(self.host, username=self.username, password=self.password, port=self.port)
except AuthenticationException:
self._ssh = None
raise ConnectionError('连接失败,请确认用户名、密码、端口或密钥文件是否有效')
except Exception as e:
self._ssh = None
raise ConnectionError('连接时出现意料外的错误:%s' % e)
def get_ssh(self):
if not self._ssh:
self._connect()
return self._ssh
class Remote(object):
...
def ssh(self, cmd, root_password=None, get_pty=False, super=False):
cmd = self._prepare_cmd(cmd, root_password, super)
stdout = self._exec(cmd, get_pty)
return stdout
def _prepare_cmd(self, cmd, root_password=None, super=False):
if self.username != 'root' and super:
if root_password:
cmd = "echo '{}'|su - root -c '{}'".format(root_password, cmd)
else:
cmd = "echo '{}'|sudo -p '' -S su - root -c '{}'".format(self.password, cmd)
return cmd
def _exec(self, cmd, gty_pty=False):
channel = self.get_ssh().get_transport().open_session()
if get_pty:
channel.get_pty()
channel.exec_command(cmd)
stdout = channel.makefile('r', -1).readlines()
stderr = channel.makefile_stderr('r', -1).readlines()
ret_code = channel.recv_exit_status()
if ret_code:
msg = ''.join(stderr) if stderr else ''.join(stdout)
raise RemoteExecError(msg)
return stdout
class Remote(object):
...
def scp(self, local_file, remote_path):
if not os.path.exists(local_file):
raise SCPError("Local %s isn't exists" % local_file)
if not os.path.isfile(local_file):
raise SCPError("%s is not a File" % local_file)
sftp = self.get_ssh().open_sftp()
try:
sftp.put(local_file, remote_path)
except Exception as e:
raise SCPError(e)
# coding: utf-8
from remote_client import RemoteClient
rc = RemoteClient('10.1.100.1', 'test', 'test_pass')
rc.ssh('whoami') # [u'test\n']
rc.scp('/tmp/test.out', '/tmp/test.out')
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有