def _establish_ssh_session(self): # Connect to remote host. try: sock = socket.create_connection( (str(self._ssh_host), self._ssh_port)) except Exception: log.error("Cannot connect to host '%s' (%s, %d).", self.name, self._ssh_host, self._ssh_port) raise # SSH handshake. ssh_session = Session() ssh_session.handshake(sock) # Verify host key. Accept keys from previously unknown hosts on first connection. hosts = ssh_session.knownhost_init() testbed_root = os.path.dirname(os.path.abspath(inspect.stack()[-1][1])) known_hosts_path = os.path.join(testbed_root, KNOWN_HOSTS_FILE) try: hosts.readfile(known_hosts_path) except ssh2.exceptions.KnownHostReadFileError: pass # ignore, file is created/overwritten later host_key, key_type = ssh_session.hostkey() server_type = None if key_type == LIBSSH2_HOSTKEY_TYPE_RSA: server_type = LIBSSH2_KNOWNHOST_KEY_SSHRSA else: server_type = LIBSSH2_KNOWNHOST_KEY_SSHDSS type_mask = LIBSSH2_KNOWNHOST_TYPE_PLAIN | LIBSSH2_KNOWNHOST_KEYENC_RAW | server_type try: hosts.checkp( str(self._ssh_host).encode('utf-8'), self._ssh_port, host_key, type_mask) except ssh2.exceptions.KnownHostCheckNotFoundError: log.warn("Host key of '%s' (%s, %d) added to known hosts.", self.name, self._ssh_host, self._ssh_port) hosts.addc( str(self._ssh_host).encode('utf-8'), host_key, type_mask) hosts.writefile(known_hosts_path) except ssh2.exceptions.KnownHostCheckMisMatchError: log.error("Host key of '%s' (%s, %d) does not match known key.", self.name, self._ssh_host, self._ssh_port) raise # Authenticate at remote host. try: if self._identity_file is None: ssh_session.agent_auth(self._username) else: ssh_session.userauth_publickey_fromfile( self._username, self._identity_file) except Exception: log.error("Authentication at host '%s' (%s, %d) failed.", self.name, self._ssh_host, self._ssh_port) ssh_session.disconnect() raise return ssh_session
def main(): user = '' password = '' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 1543)) session = Session() session.handshake(sock) session.userauth_password(user, password) session.set_blocking(False) channel = open_session(session) channel.shell() channel.write('options set --output-format=json --show-prompt=no --notify-progress=yes\n') wait_complete(sock, session, channel) channel.write('common connect-ib\n') wait_complete(sock, session, channel) channel.write('config dump-config-to-files --dir=xml\n') wait_complete(sock, session, channel) channel.write('config dump-cfg --file=1cv8.cf\n') wait_complete(sock, session, channel) channel.write('infobase-tools dump-ib --file=1cv8.dt\n') wait_complete(sock, session, channel) channel.write('common disconnect-ib\n') wait_complete(sock, session, channel) channel.write('common shutdown\n') wait_complete(sock, session, channel) channel.send_eof() channel.close() session.disconnect() exit(0)
class IrmaSFTPv2(FTPInterface): """Irma SFTPv2 handler This class handles the connection with a sftp server functions for interacting with it. """ _Exception = IrmaSFTPv2Error # ================================== # Constructor and Destructor stuff # ================================== def __init__(self, host, port, auth, key_path, user, passwd, dst_user=None, upload_path='uploads', hash_check=False, autoconnect=True): self._sess = None self._client = None super().__init__(host, port, auth, key_path, user, passwd, dst_user, upload_path, hash_check, autoconnect) def connected(self): return self._sess is not None # ============================ # Overridden private methods # ============================ def _connect(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self._host, self._port)) self._sess = Session() self._sess.handshake(sock) if self._auth == 'key': # self._pubkey_path must be generated from private key # s.userauth_publickey_fromfile(self._user, self._pubkey_path, # self._key_path, '') raise IrmaSFTPv2Error("Pub key authentication not implemented") else: self._sess.userauth_password(self._user, self._passwd) self._client = self._sess.sftp_init() def _disconnect(self, *, force=False): self._client = None if not force: self._sess.disconnect() self._sess = None def _upload(self, remote, fobj): mode = LIBSSH2_SFTP_S_IRUSR | LIBSSH2_SFTP_S_IWUSR | \ LIBSSH2_SFTP_S_IRGRP | LIBSSH2_SFTP_S_IROTH opt = LIBSSH2_FXF_CREAT | LIBSSH2_FXF_WRITE with self._client.open(remote, opt, mode) as rfh: for chunk in iter(lambda: fobj.read(1024*1024), b""): rfh.write(chunk) def _download(self, remote, fobj): with self._client.open(remote, 0, 0) as rfh: for size, data in rfh: fobj.write(data) def _ls(self, remote): with self._client.opendir(remote) as rfh: paths = (p[1].decode('utf-8') for p in rfh.readdir()) return [p for p in paths if p not in ['.', '..']] def _is_file(self, remote): return not self._is_dir(remote) def _is_dir(self, remote): st = self._client.stat(remote) return stat.S_ISDIR(st.st_mode) def _rm(self, remote): self._client.unlink(remote) def _rmdir(self, remote): self._client.rmdir(remote) def _mkdir(self, remote): mode = LIBSSH2_SFTP_S_IRUSR | \ LIBSSH2_SFTP_S_IWUSR | \ LIBSSH2_SFTP_S_IXUSR self._client.mkdir(remote, mode) def _mv(self, oldremote, newremote): self._client.rename(oldremote, newremote)
class IrmaSFTPv2(FTPInterface): """Irma SFTPv2 handler This class handles the connection with a sftp server functions for interacting with it. """ _Exception = IrmaSFTPv2Error # ================================== # Constructor and Destructor stuff # ================================== def __init__(self, host, port, auth, key_path, user, passwd, dst_user=None, upload_path='uploads', hash_check=False, autoconnect=True): self._sess = None self._client = None super().__init__(host, port, auth, key_path, user, passwd, dst_user, upload_path, hash_check, autoconnect) def connected(self): return self._sess is not None # ============================ # Overridden private methods # ============================ def _connect(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self._host, self._port)) self._sess = Session() self._sess.handshake(sock) if self._auth == 'key': # self._pubkey_path must be generated from private key # s.userauth_publickey_fromfile(self._user, self._pubkey_path, # self._key_path, '') raise IrmaSFTPv2Error("Pub key authentication not implemented") else: self._sess.userauth_password(self._user, self._passwd) self._client = self._sess.sftp_init() def _disconnect(self, *, force=False): self._client = None if not force: self._sess.disconnect() self._sess = None def _upload(self, remote, fobj): mode = LIBSSH2_SFTP_S_IRUSR | LIBSSH2_SFTP_S_IWUSR | \ LIBSSH2_SFTP_S_IRGRP | LIBSSH2_SFTP_S_IROTH opt = LIBSSH2_FXF_CREAT | LIBSSH2_FXF_WRITE with self._client.open(remote, opt, mode) as rfh: for chunk in iter(lambda: fobj.read(1024 * 1024), b""): rfh.write(chunk) def _download(self, remote, fobj): with self._client.open(remote, 0, 0) as rfh: for size, data in rfh: fobj.write(data) def _ls(self, remote): with self._client.opendir(remote) as rfh: paths = (p[1].decode('utf-8') for p in rfh.readdir()) return [p for p in paths if p not in ['.', '..']] def _is_file(self, remote): return not self._is_dir(remote) def _is_dir(self, remote): st = self._client.stat(remote) return stat.S_ISDIR(st.st_mode) def _rm(self, remote): self._client.unlink(remote) def _rmdir(self, remote): self._client.rmdir(remote) def _mkdir(self, remote): mode = LIBSSH2_SFTP_S_IRUSR | \ LIBSSH2_SFTP_S_IWUSR | \ LIBSSH2_SFTP_S_IXUSR self._client.mkdir(remote, mode) def _mv(self, oldremote, newremote): self._client.rename(oldremote, newremote)
class ssh_connection: def __init__(self, host, port, username, password): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sock.connect((host, port)) self._session = Session() self._session.handshake(self._sock) self._session.userauth_password(username, password) self._session.set_blocking(True) def exec_command(self, command, rd=True, rt=False): channel = self._session.open_session() rtn = '' try: channel.execute(command) if rd: try: size, data = channel.read() while size > 0: data = data.decode('utf-8').strip() if rt: rtn = rtn + data else: print(data) size, data = channel.read() except: pass channel.wait_eof() size, data = channel.read() data = data.decode('utf-8') print(data.strip()) channel.wait_closed channel.close() except: pass return rtn def upload(self, local, remote): print(local) print(remote) fileinfo = os.stat(local) try: chan = self._session.scp_send64(remote, fileinfo.st_mode & 0o777, fileinfo.st_size, fileinfo.st_mtime, fileinfo.st_atime) with open(local, 'rb') as local_fh: l = 0 for data in local_fh: chan.write(data) l = l+len(data) print('\rupload {0}%'\ .format(int(l/fileinfo.st_size*100)), end='', flush=True) print('\n') except ssh2.exceptions.SCPProtocolError as e: print(e) def download(self, remote, local): chan, fileinfo = self._session.scp_recv2(remote) total_size = fileinfo.st_size read_size = 0 with open(local, 'wb') as local_fh: while read_size<total_size: size, data = chan.read() local_fh.write(data) read_size = read_size + size print('\rdownload {0}%'\ .format(int(read_size/total_size*100)), end='', flush=True) print('\n') def close(self): self._session.disconnect() self._sock.close()