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
python类AutoAddPolicy()的实例源码
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 __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 Brute_Thread(ip,username,passwd):
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
global n,flag,flag1
n=n+1
try:
ssh.connect(ip,username=username,password=passwd)
except paramiko.AuthenticationException:
print Fore.RED+"[-]Username: %s\tPassword: %s failed."%(username,passwd) + Fore.RESET
else:
print Fore.GREEN+"\n********************************************************"
print "[#]Username: %s\tPassword: %s Found........!!!"%(username,passwd)
print "********************************************************"+Fore.RESET
flag=1
flag1=1
print Fore.RED+"\nFound correct password after %s attempts..." %n +Fore.RESET
return
ssh.close()
return
def get_ssh_conn(ipaddr, username, password=None, ssh_key=None):
""" Connect to remote machine through SSH Port 22 """
try:
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(AutoAddPolicy())
if ssh_key:
ssh.connect(hostname=ipaddr,
username=username,
key_filename=ssh_key,
timeout=5)
if password:
ssh.connect(hostname=ipaddr,
username=username,
password=password,
timeout=5)
ssh.close()
LOG.info("Successfully established SSH connection to %s", ipaddr)
except timeout as ex:
raise SSHError(ex.message)
except SSHException as ex:
raise SSHError(ex.message)
except error as ex:
raise SSHError(ex.strerror)
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 __init__(self, stream_output=False, **connect_kwargs):
logger.vdebug('ssh.__init__')
super(SSHClient, self).__init__()
self._streaming = stream_output
default_connect_kwargs = {
'username': cfme_performance['appliance']['ssh']['username'],
'password': cfme_performance['appliance']['ssh']['password'],
'hostname': cfme_performance['appliance']['ip_address'],
'port': 22,
'timeout': 10,
'allow_agent': False,
'look_for_keys': False,
'gss_auth': False
}
# Overlay defaults with any passed-in kwargs and store
default_connect_kwargs.update(connect_kwargs)
self._connect_kwargs = default_connect_kwargs
self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
_client_session.append(self)
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 _checkAccessUsingKey(self, host, user, port=SSH_DEFAULT_PORT):
"""
check if we have SSH access via user by using SSH keys ?
Having an AuthenticatioException is one of the standard ways.
:param Lab host: hostname
:param str user: user to login
:return: None if no connection. Returns instance of SSH connection if OK
:rtype: None/object
>>> self._checkAccessUsingKey(host, user, port=SSH_DEFAULT_PORT)
"""
#client = paramiko.SSHClient()
client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# to ignore user .ssh homedir keys : use those options allow_agent=False, look_for_keys=False)
# CAUTION with those option : exception is SSHException (instead of AuthenticationException)
client.connect(host, port, user, key_filename=self.privateKey)
client.get_transport().set_keepalive(self.__class__.defaultHeartbeat)
return client
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 login(self, switch):
""" login
logs into specified switch """
# set up ssh client
ssh_setup = paramiko.SSHClient()
# add missing host key policy (set as auto)
ssh_setup.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# connect to switch
ssh_setup.connect(
switch,
username=self.user,
password=self.user_pw,
look_for_keys=False,
allow_agent=False,
)
# set up transport channel for session
transport = ssh_setup.get_transport()
# invoke session
self.ssh_session = transport.open_session()
# set up for interactive mode, multiple commands - pty
self.ssh_session.get_pty()
# invoke session's shell
self.ssh_session.invoke_shell()
# keep session active with parameters while class is initialized
self.ssh_session.keep_this = ssh_setup
def login(self, switch):
""" login
logs into specified switch """
# set up ssh client
ssh_setup = paramiko.SSHClient()
# add missing host key policy (set as auto)
ssh_setup.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# connect to switch
ssh_setup.connect(
switch,
username=self.user,
password=self.user_pw,
look_for_keys=False,
allow_agent=False,
)
# set up transport channel for session
transport = ssh_setup.get_transport()
# invoke session
self.ssh_session = transport.open_session()
# set up for interactive mode, multiple commands - pty
self.ssh_session.get_pty()
# invoke session's shell
self.ssh_session.invoke_shell()
# keep session active with parameters while class is initialized
self.ssh_session.keep_this = ssh_setup
def sshclient_execmd_ps(hostname,execmd,port=port, username=username, password=password):
paramiko.util.log_to_file("paramiko.log")
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname=hostname, port=port, username=username, password=password)
stdin, stdout, stderr = s.exec_command (execmd)
stdin.write("Y") # Generally speaking, the first connection, need a simple interaction.
out = stdout.read()
print out
s.close()
return out