def sshCommand(ip, user, passwd, command):
try:
key = paramiko.RSAKey.from_private_key_file("/home/ubuntu/data/PyHack/qCloud")
except paramiko.PasswordRequiredException:
pass
client = paramiko.SSHClient()
#client.load_host_keys('/home/ubuntu/.ssh/kow')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, username = user, pkey = key)
sshSession = client.get_transport().open_session()
if sshSession.active:
sshSession.exec_command(command)
print sshSession.recv(1024)
return
python类SSHClient()的实例源码
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
def check(ip, port, timeout):
user_list = ['root', 'admin', 'oracle', 'weblogic']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for user in user_list:
for pass_ in PASSWORD_DIC:
pass_ = str(pass_.replace('{user}', user))
try:
ssh.connect(ip, port, user, pass_, timeout=timeout, allow_agent = False, look_for_keys = False)
ssh.exec_command('whoami',timeout=timeout)
if pass_ == '': pass_ = "null"
return u"?????????%s????%s" % (user, pass_)
except Exception, e:
if "Unable to connect" in e or "timed out" in e: return
finally:
ssh.close()
def ssh_execute_cli(cli, sff_locator):
""" """
remoteConnectionSetup = paramiko.SSHClient()
remoteConnectionSetup.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remoteConnectionSetup.connect(sff_locator,
username='cisco', password='cisco',
allow_agent=False, look_for_keys=False)
# invoke the shell so can send multiple commands
sshChannel = remoteConnectionSetup.invoke_shell()
# make sure in enable mode so we can configure the router
is_enabled = sshChannel.recv(1000)
if "#" not in is_enabled:
enable_router(sshChannel)
# execute the necessary commands to configure the router
send_command_and_wait_for_execution(sshChannel, "conf t\n", "#", False)
send_command_and_wait_for_execution(sshChannel, cli + '\n', "#", False)
remoteConnectionSetup.close() # close the connection
def exec_remote_list_of_cmds(hostname, commands, username='root', port=22, sudo=False):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port=port, username=username)
returned_array = []
for command in commands:
log.debug('command to launch in ssh in {}: {}'.format(hostname, command))
stdin, stdout, stderr = client.exec_command(command)
out = stdout.read().decode('utf-8')
err = stderr.read().decode('utf-8')
returned_array.append({'out': out, 'err': err})
log.debug('commnad launched / out: {} / error: {}'.format(out, err))
client.close()
return returned_array
def exec_remote_list_of_cmds_dict(hostname, list_dict_commands, username='root', port=22, ssh_key_str='', sudo=False):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if len(ssh_key_str) > 0:
# TODO: make ssh_key login
pass
else:
client.connect(hostname, port=port, username=username)
returned_array = list_dict_commands.copy()
i = 0
for command in list_dict_commands:
log.debug('command to launch in ssh in {}: {}'.format(hostname, command['cmd']))
stdin, stdout, stderr = client.exec_command(command['cmd'])
returned_array[i]['out'] = stdout.read().decode('utf-8')
returned_array[i]['err'] = stderr.read().decode('utf-8')
log.debug('commnad launched / out: {} / error: {}'.format(returned_array[i]['out'], returned_array[i]['err']))
i = i + 1
client.close()
return returned_array
def exec_remote_list_of_cmds(hostname, commands, username='root', port=22, sudo=False):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port=port, username=username)
returned_array = []
for command in commands:
log.debug('command to launch in ssh in {}: {}'.format(hostname, command))
stdin, stdout, stderr = client.exec_command(command)
out = stdout.read().decode('utf-8')
err = stderr.read().decode('utf-8')
returned_array.append({'out': out, 'err': err})
log.debug('commnad launched / out: {} / error: {}'.format(out, err))
client.close()
return returned_array
def exec_remote_list_of_cmds_dict(hostname, list_dict_commands, username='root', port=22, ssh_key_str='', sudo=False):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if len(ssh_key_str) > 0:
# TODO: make ssh_key login
pass
else:
client.connect(hostname, port=port, username=username)
returned_array = list_dict_commands.copy()
i = 0
for command in list_dict_commands:
log.debug('command to launch in ssh in {}: {}'.format(hostname, command['cmd']))
stdin, stdout, stderr = client.exec_command(command['cmd'])
returned_array[i]['out'] = stdout.read().decode('utf-8')
returned_array[i]['err'] = stderr.read().decode('utf-8')
log.debug('commnad launched / out: {} / error: {}'.format(returned_array[i]['out'], returned_array[i]['err']))
i = i + 1
client.close()
return returned_array
def retrieve_out_files(party_out_files,
remote_dest_folder, local_dest_folder):
for i, f in enumerate(party_out_files):
ip = public_ips[i] if USE_PUB_IPS else private_ips[i]
key = paramiko.RSAKey.from_private_key_file(KEY_FILE)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=ip, username=REMOTE_USER, pkey=key)
sftp = client.open_sftp()
sftp.chdir(os.path.join('secure-distributed-linear-regression',
remote_dest_folder))
logger.info(
'Retrieving .exec file {0} from {1} in {2}'.format(
f, remote_dest_folder, ip))
sftp.get(f, os.path.join(local_dest_folder, f))
client.close()
def ssh_connect(server_name,script_path,script_parameter):
pkey = paramiko.RSAKey.from_private_key_file(dao_config.key_address)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
command = "bash" + ' ' +script_path + ' ' + script_parameter
print(command)
ssh.connect(
hostname=server_name,
port=22,
username='root',
pkey=pkey)
stdin, stdout, stderr = ssh.exec_command(command)
# out_log_all=stdout.readlines().decode()
out_log_all = stdout.read().decode()
err_log_all=stderr.read().decode()
ssh.close()
if err_log_all:
return err_log_all
return out_log_all
def ssh(config, host):
"""
Check that a host is running SSH
:param config: Unused
:param host: The host to check
:return: 3-tuple of (success, name, message)
success: Boolean value indicating if there is a problem or not
name: DNS name
message: String describing the status
"""
del config
name = host
try:
ssh_conn = paramiko.SSHClient()
ssh_conn.set_missing_host_key_policy(
paramiko.client.MissingHostKeyPolicy())
ssh_conn.connect(host)
return True
except (paramiko.BadHostKeyException, paramiko.AuthenticationException,
paramiko.SSHException, socket.error) as e:
return (False, name, "Unable to SSH to %s %s %s"
% (host, e.__class__, e))
def __init__(self, hostname, port, username, password, use_scp=False, scp_sanitize=None):
"""
:param hostname: ssh server hostname or ip
:param port: ssh server port
:param username: ssh login username
:param password: ssh login password
:param use_scp: use the SCP protocol for transferring files instead of SFTP (default: False)
:param scp_sanitize: sanitization function used on filenames passed to the scp module, if used. (defaut: no sanitization)
"""
self._hostname = hostname
self._port = port
self._username = username
self._password = password
self._use_scp = use_scp
self._scp_sanitize = scp_sanitize if callable(scp_sanitize) else lambda s:s
if self._use_scp and not scp_imported:
raise Exception("The scp package needs to be installed in order to copy files with scp")
self._paramiko = paramiko.SSHClient()
self._paramiko.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def open(self):
"""Open the ssh connection"""
key_str = io.StringIO(self.config['key'])
pkey = paramiko.RSAKey.from_private_key(key_str)
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
self.client.connect(
self.config['hostname'], username=self.config['username'],
pkey=pkey, timeout=60, banner_timeout=60)
self.transport = self.client.get_transport()
self.transport.set_keepalive(60)
self.script_filename = self.get_tmp_script_filename()
def _connect(self):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.url.host, self.url.port or 22, self.url.user, self.url.password)
return scp.SCPClient(client.get_transport())
def test_init(self, mock_conn, mock_set):
sshclient.SSHClient('ip', 'username', 'password')
mock_conn.assert_called_with(
'ip', username='username', password='password', pkey=None,
key_filename=None, look_for_keys=False, allow_agent=False)
def test_ssh_except(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(['info'], mock_channel),
fake_channel_file(['err']))
mock_channel.recv_exit_status.return_value = -1
client = sshclient.SSHClient('ip', 'username', password='password',
log=mock_log)
self.assertRaises(sshclient.SshExecCmdFailure, client.ssh,
'fake_command', output=True)
def test_scp(self, mock_open, mock_conn, mock_set):
mock_log = mock.Mock()
mock_sftp = mock.Mock()
mock_open.return_value = mock_sftp
client = sshclient.SSHClient('ip', 'username', password='password',
log=mock_log)
client.scp('source_file', 'dest_file')
mock_log.info.assert_called()
mock_sftp.put.assert_called_with('source_file', 'dest_file')