def connect(self): """ Possible exceptions: BadHostKeyException, AuthenticationException, SSHException but it dosn't matter which one it is, just logging it. """ self.set_missing_host_key_policy(AutoAddPolicy()) try: SSHClient.connect(self, hostname=self.address, username=self.credentials.username, password=self.credentials.password) except Exception as ex: LOGGER.critical(ex) return False self.connected = True return True
def __connect(self, auto_add: bool = False): """Open connection to remote host.""" self.ssh_client = SSHClient() if auto_add: self.ssh_client.set_missing_host_key_policy(AutoAddPolicy()) else: self.ssh_client.load_system_host_keys() self.ssh_client.connect( self.host, username=self.user, port=self.port, passphrase=self.passphrase, password=self.password, ) self.scp_client = SCPClient(self.ssh_client.get_transport()) return self.ssh_client
def put_file_on_target(self, ip, file_name): """ SSH to a host and touch a file there. We can later check for this files existence to determine whether a kickstart completed successfully. :param ip: (string) IP address of host :param file_name: name of file to create :return: """ ssh = SSHClient() ssh.set_missing_host_key_policy( AutoAddPolicy()) # wont require saying 'yes' to new fingerprint ssh.connect(ip, username=self.ssh_user, password=self.ssh_password) ssh.exec_command('touch ' + file_name) ssh.close() return
def __connect(self): try: self.client = SSHClient() self.client.load_system_host_keys() self.client.set_missing_host_key_policy(AutoAddPolicy()) self.client.connect(self.host, username=self.user, key_filename=self.ssh_key_filepath, look_for_keys=True, timeout=5000) self.sftp = self.client.open_sftp() except AuthenticationException as error: logger.error(error) raise error finally: return self.client
def pull_one(self, unit, imsi): #Open Soracom tunnel (120 seconds) self.soracom.tunnel(imsi, 60) ip = self.soracom.get_ip() portnumber = self.soracom.get_port() #Open FTP print("Connecting to " + str(unit) + " at " + ip + " on port " + str(portnumber)) client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(hostname=ip, port=portnumber, username='******', password='******', timeout=60) sftp = client.open_sftp() print("FTP Connected") #Timestamp now = datetime.now() #Create directory for new service logfile destination = 'logs/' + str(unit) + '/' + now.strftime( '%Y') + '/' + now.strftime('%m') + '/' + now.strftime( '%d') + '/' + now.strftime('%H') + "/lvm-service-log-01.txt" self.last_path = 'logs/' + str(unit) + '/' + now.strftime( '%Y') + '/' + now.strftime('%m') + '/' + now.strftime( '%d') + '/' + now.strftime('%H') + '/' self.s3_path = str(unit) + '/' + now.strftime( '%Y') + '/' + now.strftime('%m') + '/' + now.strftime( '%d') + '/' + now.strftime('%H') + '/lvm-service-log-01.txt' os.makedirs(self.last_path) #Transfer logfile sftp.get('mnt/data/lvm/logs/lvm-service-log-01.txt', destination) print("One file downloaded") #Close FTP connection sftp.close() print("Connection to " + str(unit) + " closed")
def __connect(self): """Open connection to remote host.""" try: self.client = SSHClient() self.client.load_system_host_keys() self.client.set_missing_host_key_policy(AutoAddPolicy()) pk = None with open(self.ssh_key_filepath) as keyfile: pk = RSAKey.from_private_key(keyfile, password=self.passphrase) if pk is None: logger.error(f"private key {self.ssh_key_filepath} not found") exit(1) max_errors = 5 errors = 0 while errors < max_errors: try: self.client.connect( hostname=self.host, username=self.user, passphrase=self.passphrase, pkey=pk, look_for_keys=True, auth_timeout=30, timeout=60, ) self.scp = SCPClient(self.client.get_transport()) break except NoValidConnectionsError as e: logger.exception("Unable to connect") errors = errors + 1 if errors == 5: raise Exception( "Too many connection failures. Giving up.") time.sleep(5) except AuthenticationException as error: logger.exception("Authentication failed") raise error except SSHException as error: logger.exception("SSH exception") raise error except Exception as error: logging.exception("unexpected error") raise error finally: return self.client
def connection(ip_address, username): # try to establish connection to remote virtual machine ssh = SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(AutoAddPolicy()) # loop over all of the private keys in config and see if we can connect with any of them num_lines = sum(1 for line in open(os.path.expanduser("~/.ssh/config"))) for index in range(0, num_lines): key = get_key_for_host(ip_address, index) ki = RSAKey.from_private_key_file(key) try: ssh.connect(ip_address, username=username, pkey=ki, banner_timeout=6000000) return ssh except: continue raise SCPException("No valid private key in ~/.ssh/config")
def copy_app_to_pc(self, app_name): self._ssh_client.set_missing_host_key_policy(AutoAddPolicy()) self._ssh_client.connect(self._ip, username=self._username, password=self._mypasswd) sftp = self._ssh_client.open_sftp() f = sftp.open("/tmp/" + app_name, 'wb') f.write(open(self._get_my_path() + "/iperf_app/" + app_name).read()) f.close() sftp.close() self._ssh_client.close() win_tmp_path, stderr = self._run_cmd("cygpath -w /tmp") ret, stderr = self._run_cmd("pwd") self._mylogger.debug("".join(ret)) return ("".join(win_tmp_path).rstrip() + "\\" + app_name).replace( "\\", "/")
def copy_file_to_webserver(ip): """Copy the connect.inc.php file to the web server with IP address = ip""" ssh = SSHClient() username = getpass.getuser() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.load_system_host_keys() key_path = "/home/" + username + "/.ssh/inframindwebserver.pem" ssh.connect(ip, username='******', key_filename=key_path) scp = SCPClient(ssh.get_transport()) scp.put('../synergy/includes/connect.inc.php', '/var/www/html/inframind/synergy/includes') ssh.close()
def open_ssh_connection(self): logger.debug("Establishing SSH connection with '%s' on '%s'", str(self.user_name), self.host_ip) self.set_missing_host_key_policy(AutoAddPolicy()) try: self.connect(self.host_ip, username=self.user_name, password=self.password, key_filename=self.key_filename) except (SSHException, socket.error) as err: logger.error("Unable to establish SSH connection with '%s'", self.host_ip) raise logger.debug("SSH connection successful with '%s' on '%s'", str(self.user_name), self.host_ip) logger.info("Successfully connected to '%s'", self.host_ip) return True
def _set_user_ssh_session(self, debug=False): """ Internal. Opens a ssh session using user's keys """ self.user_ssh = SSHClient() self.user_ssh.set_missing_host_key_policy(AutoAddPolicy()) if debug: paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG) try: self.user_ssh.connect( self.host, username=self.userid, ) except AuthenticationException as err: sys.exit(err) self.sftp = self.user_ssh.open_sftp()
def connection(self): """Open Connection to remote host.""" try: client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect( self.host, username=self.user, passphrase=self.passphrase, key_filename=self.ssh_key_filepath, timeout=5000, ) return client except AuthenticationException as e: print(f"Authentication failed: did you remember to create an SSH key? {e}") raise e
def oxe_runtel(host, port, password): """RUNTEL start telephone Args: host (TYPE): Description port (TYPE): Description password (TYPE): Description """ client = SSHClient() # use the paramiko SSHClient client.set_missing_host_key_policy( AutoAddPolicy()) # automatically add SSH key try: client.connect(host, port, username='******', password=password) except AuthenticationException: print('*** Failed to connect to {}:{}'.format(host, port)) client.exec_command('RUNTEL\n') client.close()
def shell(self, cmd: str): if self.accessible == False: print("No access info...") return False pkey_file = self.pkey.open() client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(hostname=self.host, pkey=Ed25519Key.from_private_key( pkey_file, self.passphrase), passphrase=self.passphrase, username=self.user) _, _, stderr = client.exec_command(cmd) for line in stderr: print(line, file=sys.stderr) client.close()
def run(self): sshConnection = SSHClient() sshConnection.set_missing_host_key_policy(AutoAddPolicy()) try: sshConnection.connect(self.targetIp, port=int(self.portNumber), username=self.username, password=self.password, timeout=int(self.timeoutTime), allow_agent=False, look_for_keys=False) self.status = 'Succeeded' sshConnection.close() except Exception, e: if "Error reading SSH protocol" in str(e): self.status = 'timeout' else: self.status = 'Failed'
def __init__(self): sshcli.set_missing_host_key_policy(AutoAddPolicy()) argparser.add_argument("-STA", "--start", help="Wokes up server", action="store_true") argparser.add_argument("-STP", "--stop", help="Stops server", action="store_true") if len(argv) == 1: argparser.print_help(stderr) exit(1) elif argparser.parse_args().start: self.door(argumentto=1) elif argparser.parse_args().stop: self.door(argumentto=2)
def __init__(self): self.client = SSHClient() self.client.set_missing_host_key_policy(AutoAddPolicy()) try: self.client.connect( hostname=os.getenv('TEST_SSH_HOST'), port=int(os.getenv('TEST_SSH_PORT', 22)), username=os.getenv('TEST_SSH_USER'), password=os.getenv('TEST_SSH_PASSWORD'), ) except AuthenticationException: print("Authentication failed, please verify your credentials") except SSHException as sshException: print(f"Could not establish SSH connection {sshException}") return
def job(self, device, _): ssh_client = SSHClient() if self.missing_host_key_policy: ssh_client.set_missing_host_key_policy(AutoAddPolicy()) if self.load_known_host_keys: ssh_client.load_system_host_keys() ssh_client.connect(device.ip_address, username=device.username, password=device.password, look_for_keys=self.look_for_keys) self.transfer_file(ssh_client, self.sub(self.source_file, locals()), self.sub(self.destination_file, locals())) ssh_client.close() return { 'success': True, 'result': f'File {self.source_file} transferred successfully' }
def create_ssh_client(username, hostname, port=22, password=None, key_filename=None): """Creates (and returns) an SSHClient. Auth'n is via publickey.""" log = logging.getLogger("create_ssh_client") log.warn(">>> DEPRECATION IN PROGRESS [create_ssh_client] <<<") ssh_client = SSHClient() ssh_client.load_system_host_keys() ssh_client.set_missing_host_key_policy(AutoAddPolicy()) ssh_client.connect(username=username, hostname=hostname, port=port, password=password, key_filename=key_filename) return ssh_client
def connect(self): from paramiko import SSHClient, AutoAddPolicy if self.logfile: import logging logging.basicConfig(filename=self.logfile) log = logging.getLogger("paramiko") log.setLevel(logging.DEBUG) self.client = SSHClient() self.client.set_missing_host_key_policy(AutoAddPolicy()) self.client.connect(self.hostname, username=self.username, password=self.password) return self
def vagrant_topo_verify(self): for dev in devices_all: try: client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(dev[0], port=int(dev[1]), username='******', password='******') devices_online.append(dev[2]) # stdin, stdout, stderr = client.exec_command("ifconfig -a | grep 'HWaddr\|inet addr'") stdin, stdout, stderr = client.exec_command( "ifconfig -a | grep 'HWaddr'") # print stdout.read().replace('inet addr:127.0.0.1 Mask:255.0.0.0', '') ind = next(index for (index, d) in enumerate(topo_yaml['nodes']) if d["name"] == dev[2]) outp = [] outp = stdout.read().replace('Link', '').replace('HWaddr', '').replace( 'encap:Ethernet', '').split() l_name_dict = {} if 'eth0' in outp: del outp[outp.index('eth0'):outp.index('eth0') + 2] if 'fwd_ew' in outp: del outp[outp.index('fwd_ew'):outp.index('fwd_ew') + 2] if 'Mg0_RP0_CPU0_0' in outp: del outp[outp.index('Mg0_RP0_CPU0_0' ):outp.index('Mg0_RP0_CPU0_0') + 2] if 'fwdintf' in outp: del outp[outp.index('fwdintf'):outp.index('fwdintf') + 2] print outp for i in range(0, len(outp) / 2): l_name_dict[topo_yaml['nodes'][ind]['interfaces'][i] ['link-name']] = [ outp[i * 2], outp[i * 2 + 1] ] hosts_w_macs[dev[2]] = l_name_dict print hosts_w_macs client.close() except Exception, e: print str(e)
def setup(self) -> None: self.ssh = SSHClient() self.ssh.load_system_host_keys() self.ssh.set_missing_host_key_policy(AutoAddPolicy()) self.ssh.connect( hostname=self.flags.tunnel_hostname, port=self.flags.tunnel_port, username=self.flags.tunnel_username, key_filename=self.flags.tunnel_ssh_key, passphrase=self.flags.tunnel_ssh_key_passphrase, ) logger.info( 'SSH connection established to %s:%d...' % ( self.flags.tunnel_hostname, self.flags.tunnel_port, ), ) self.transport = self.ssh.get_transport()
def main(): output = '' with SSHClient() as client: client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(hostname='10.1.30.101', username='******', password='******', look_for_keys=False) session = client.invoke_shell() _output = get_output(session) output += _output if find_prompt(_output): cmd_output = send_command(session, 'terminal length 0') output += cmd_output cmd_output = send_command(session, 'show running-config') output += cmd_output print(output.strip())
def connect(sw, user, pw, ssh_timeout=120): """actually connects to a switch. returns a paramiko connection""" try: conn = SSHClient() conn.set_missing_host_key_policy(AutoAddPolicy()) conn.connect(sw, username=user, password=pw, timeout=ssh_timeout) except AuthenticationException as e: print('') print( 'ATTENTION: Authentication failed, please verify your credentials') print('') except SSHException as e: print('') print('ATTENTION: Unable to establish SSH connection: %s' % e) print('') return conn
def init_client(self): ssh = SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(AutoAddPolicy()) if self.pub_key: pkey = RSAKey.from_private_key_file(self.pub_key) ssh.connect(hostname=self.hostname, username=self.username, pkey=pkey, look_for_keys=True) elif self.password: ssh.connect(hostname=self.hostname, port=self.ssh_port, username=self.username, password=self.password, look_for_keys=True) else: raise ValueError('password or pub_key is required') return ssh
def ssh_connect_ok(host, user=None): if not user: if configuration.settings.target_user: user = configuration.settings.target_user else: user = getpass.getuser() client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) priv_key = os.path.join(configuration.settings.playbooks_root_dir, "env/ssh_key") if not os.path.exists(priv_key): return False, "FAILED:SSH key(s) missing from ansible-runner-service" conn_args = { "hostname": host, "username": user, "timeout": configuration.settings.ssh_timeout, "key_filename": [priv_key] } try: client.connect(**conn_args) except socket.timeout: return False, "TIMEOUT:SSH timeout waiting for response from " \ "'{}'".format(host) except (AuthenticationException, SSHException): return False, "NOAUTH:SSH auth error - passwordless ssh not " \ "configured for '{}'".format(host) except NoValidConnectionsError: return False, "NOCONN:SSH target '{}' not contactable; host offline" \ ", port 22 blocked, sshd running?".format(host) except socket.gaierror: return False, "NOCONN:SSH error - '{}' not found; check DNS or " \ "/etc/hosts".format(host) else: client.close() return True, "OK:SSH connection check to {} successful".format(host)
def test_ssh(id, token): ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) port = 2200 + int(id) print(port) try: ssh.connect(hostname='172.17.0.1', username='******', password=token, port=port) print('OK') ssh.close() return True except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e: print('SSH error') return False
def __init__(self, hostname: str, key_filename: str, username: str) -> None: assert isinstance(hostname, str) assert isinstance(key_filename, str) assert isinstance(username, str) self._ssh = SSHClient() self._ssh.set_missing_host_key_policy(AutoAddPolicy()) self._ssh.connect(hostname, key_filename=key_filename, username=username, timeout=4, banner_timeout=4, auth_timeout=4) return
def Connection_O2(bus, Adress, Login, Password): Ad = Adress Log = Login Pass = Password ssh_O2 = SSHClient() # Создаем клиент подключения ssh_O2.set_missing_host_key_policy( AutoAddPolicy()) # Создаем стек ключей подлкючения для доступа ssh_O2.connect(Ad, port=22, username=Log, password=Pass) # Подключаемся exe_Upload = "put [interface get [find name=O2] rx-byte]" exe_Download = "put [interface get [find name=O2] tx-byte]" Upload = ssh_O2.exec_command(exe_Upload)[1].read() Download = ssh_O2.exec_command(exe_Download)[1].read() Summa = Trafic(Upload, Download) Trafic_Down(Summa, bus)
def git_clone(hostname, username="******", gitdir='vaelstmpredictor', gituser='******', branchname='conv1d_model', port=22, verbose=True, private_key='id_ecdsa'): key_filename = os.environ['HOME'] + '/.ssh/{}'.format(private_key) try: ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect(hostname, key_filename=key_filename) except NoValidConnectionsError as error: warning_message(error) ssh.close() return command = [] command.append('git clone https://github.com/{}/{}'.format( gituser, gitdir)) command.append('cd {}'.format(gitdir)) command.append('git pull') command.append('git checkout {}'.format(branchname)) command.append('git pull') command = '; '.join(command) info_message('Executing {} on {}'.format(command, hostname)) try: stdin, stdout, stderr = ssh.exec_command(command) except NoValidConnectionsError as error: warning_message(error) ssh.close() return info_message('Printing `stdout`') # print_ssh_output(stdout) info_message('Printing `stderr`') # print_ssh_output(stderr) ssh.close() info_message('SSH Closed on Git Clone') print("Git Clone Executed Successfully")