def ssh_login(ip, username, password): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) is_ipv4_timeout = False is_ipv6_timeout = False while True: try: if not is_ipv4_timeout: print('[+]Try to connect to {}:22'.format(ip['v4'])) sock.connect((ip['v4'], 22)) elif not is_ipv6_timeout: sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) print('[+]Try to connect to {}:22'.format(ip['v6'])) sock.connect((ip['v6'], 22)) else: print( '[-]Cannot connect to host, rerun this script and try again' ) exit(0) break except TimeoutError as ex: print(ex) if not is_ipv4_timeout: is_ipv4_timeout = True elif not is_ipv6_timeout: is_ipv6_timeout = True except ConnectionRefusedError as ex: print(ex) print('[+] Sleep 5s and then retry ...') time.sleep(5) print('[+]Connect success') session = Session() session.handshake(sock) session.userauth_password(username, password) return session
def _connect(self): try: if self.session == None: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.hostname, 22)) self.session = Session() self.session.handshake(sock) if self.ssh_identity_file != None: self.session.userauth_publickey_fromfile( self.ssh_username, self.ssh_identity_file, '', None) elif self.ssh_password != None: self.session.userauth_password(self.ssh_username, self.ssh_password) elif self.ssh_username == None: user = os.getlogin() self.session.agent_auth(user) else: self.session.agent_auth(self.ssh_username) self.channel = self.session.open_session() except: self.channel = None self.session = None raise BadSSHHost( "Could not establish an SSH connection to host %s" % (self.hostname, ))
def executeMT(self, execOnMT, ipToCon): host = ipToCon user = self.loginSsh passwd = self.passwdSsh port = int(self.portSsh) timeout = self.timeoutSsh i = 0 while (True): if i < 3: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) session = Session() session.handshake(sock) session.userauth_password(user, passwd) channel = session.open_session() channel.execute(execOnMT) channel.wait_eof() channel.close() channel.wait_closed() except Exception as e: logging.warn('deamonMT: %s', (e)) else: logging.info('deamonMT: ssh commands has been sent, SUCCESS') break finally: sock.close() time.sleep(1) i += 1 else: logging.info("deamonMT: ssh can't connect to host: %s", (host)) break
def DOS_attack_SSH(): host = TARGET password = input('enter password > ') usr = os.getlogin() try: while True: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TARGET, PORT)) print(f'ssh connected: {TARGER} on PORT {PORT}') # SSH exclusive msg sending session = Session() session.handshake(s) session.agent_auth(usr) # trying an ssh session try: channel = session.open_session() channel.execute('echo "u heb bin heked";') channel.close() except: pass global Breach_count Breach_count += 1 print(Breach_count) s.close() except Exception as e: print(e)
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 test_non_blocking_handshake(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = Session() session.set_blocking(0) while session.handshake(sock) == LIBSSH2_ERROR_EAGAIN: continue
def test_set_flag(self): self.session = Session() self.session.flag(LIBSSH2_FLAG_COMPRESS, True) self.set_method_preferences(TEST_PREFERENCES) self.session.handshake(self.sock) response = self.session.methods(LIBSSH2_METHOD_COMP_CS) assert not b'none' == response
def configure_server(): """ Function to configure servers :param : """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((listToString(SERVER[0]), 22)) # assign to session class session = Session() # set up 3 way handshake logging.info('Setting up 3-way handshake') session.handshake(sock) logging.debug('Username is %s', USERNAME) logging.debug('password %s', PASSWORD) session.userauth_password(USERNAME, PASSWORD) channel = session.open_session() channel.execute( "apt-get update -y; apt-get install apache2 -y; systemctl start apache2.service" ) size, data = channel.read() # while (size > 0): # print(data.decode()) # size, data = channel.read() channel.close() print("Exit status : {0}", format(channel.get_exit_status()))
def test_callback_set(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = Session() # These variables have to be attached to the class scope # in order to be modified inside the callback. Local scope # is not passed into the callback. self.send_called = False self.recv_called = False def _send_callback(fd, buf, flags): self.send_called = True return sock.sendall(buf, flags) def _recv_callback(fd, length, flags): self.recv_called = True return sock.recv(length, flags) session.set_recv_callback(_recv_callback) session.set_send_callback(_send_callback) session.handshake(sock) self.assertTrue(self.send_called) self.assertTrue(self.recv_called)
def ssh2_ssh(host, port=22, user='******', password='******'): global command # Make socket, connect sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) # Initialise session = Session() session.handshake(sock) session.userauth_password(user, password) # Public key blob available as identities[0].blob # Channel initialise, exec and wait for end channel = session.open_session() channel.execute(command) channel.wait_eof() channel.close() channel.wait_closed() # Print output output = b'' size, data = channel.read() while size > 0: output += data size, data = channel.read() # Get exit status output = output.decode("utf-8").strip()
def host_scp_send(self, local_file, remote_file): assert self.operation_system == 'Linux', "[Assert Error] Only Linux OS is supported!" file_stat = os.stat(local_file) # Make socket, connect sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host_ip, self.port)) # Initialise session = Session() session.handshake(sock) userauth_list = session.userauth_list(self.username) self.LOG.print_log( 'DEBUG', "In host {}, user {} authentication list is: {}.".format( self.host_ip, self.username, userauth_list)) session.userauth_password(self.username, self.password) # Channel initialise, exec and wait for end self.LOG.print_log( 'INFO', "Send local file {} to Host {} at {}.".format( local_file, self.host_ip, remote_file)) try: channel = session.scp_send(remote_file, file_stat.st_mode & 777, file_stat.st_size) with open(local_file, 'rb') as local_fh: for data in local_fh: channel.write(data) channel.send_eof() channel.wait_eof() channel.wait_closed() except Exception as err: self.LOG.print_log('ERROR', str(err)) assert False, "[Assert Error] Something wrong during scp send!"
def main(): args = parser.parse_args() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((args.host, args.port)) s = Session() s.handshake(sock) print(args.user) print(args.host) print(args.port) #s.userauth_publickey_fromfile(args.user, "~/.ssh/id_rsa") passwd = input('Enter your password: '******'rb') as local_fh: for data in local_fh: chan.write(data) taken = datetime.now() - now rate = (fileinfo.st_size / (1024000.0)) / taken.total_seconds() print("Finished writing remote file in %s, transfer rate %s MB/s" % (taken, rate))
def _init(self, retries=1): self.session = Session() if self.kex_algorithms is not None: self.session.method_pref(LIBSSH2_METHOD_KEX, self.kex_algorithms) if self.ciphers is not None: self.session.method_pref(LIBSSH2_METHOD_CRYPT_CS, self.ciphers) self.session.method_pref(LIBSSH2_METHOD_CRYPT_SC, self.ciphers) if self.MACs is not None: self.session.method_pref(LIBSSH2_METHOD_MAC_CS, self.MACs) self.session.method_pref(LIBSSH2_METHOD_MAC_SC, self.MACs) if self.timeout: # libssh2 timeout is in ms self.session.set_timeout(self.timeout * 1000) try: self.session.handshake(self.sock) except Exception as ex: while retries < self.num_retries: return self._connect_init_retry(retries) msg = "Error connecting to host %s:%s - %s" logger.error(msg, self.host, self.port, ex) if isinstance(ex, SSH2Timeout): raise Timeout(msg, self.host, self.port, ex) raise try: self.auth() except Exception as ex: while retries < self.num_retries: return self._connect_init_retry(retries) msg = "Authentication error while connecting to %s:%s - %s" raise AuthenticationException(msg, self.host, self.port, ex) self.session.set_blocking(0) if self.keepalive_seconds: self.configure_keepalive() self._keepalive_greenlet = self.spawn_send_keepalive()
def _connect(self): """create a connection for this thread""" self._abort = False size_bk = 0 if self.parent_ui: size_bk += self.parent_ui.progress["maximum"] self.parent_ui.progress.configure(mode="indeterminate", maximum=100) self.parent_ui.progress.start() if self._mode == "SFTP": try: sock = socket(AF_INET, SOCK_STREAM) sock.settimeout(10) sock.connect((self._host, self._port)) cli = Session() cli.set_timeout(10000) cli.handshake(sock) cli.userauth_password(self._name, self._passwd) cli.set_timeout(0) self._connection = cli.sftp_init() except Timeout: self._abort = True messagebox.showerror("Connection Error", "Connection timeout on login.") except AuthenticationError as e: self._abort = True messagebox.showerror("Authentication Error", "Wrong login credentials.") except Exception as e: print(type(e), e.args, str(e)) self._abort = True messagebox.showerror( "Connection Error", "Could not establish a connection.\n%s" % e) finally: if self.parent_ui: self.parent_ui.progress.stop() self.parent_ui.progress.configure(value=0, mode="determinate", maximum=size_bk) else: # FTP try: ftp = FTP() ftp.encoding = self._enc ftp.connect(self._host, self._port, 10) ftp.login(self._name, self._passwd) self._connection = ftp except Exception as e: self._abort = True messagebox.showerror("Connection Error", str(e)) finally: if self.parent_ui: self.parent_ui.progress.stop() self.parent_ui.progress.configure(value=0, mode="determinate", maximum=size_bk)
def login(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.ip, 22)) self.session = Session() self.session.handshake(self.sock) self.session.userauth_password(self.user, self.password)
def main(): args = parser.parse_args() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((args.host, args.port)) s = Session() s.handshake(sock) # Agent connections cannot be used as non-blocking s.agent_auth(args.user) # Now we can set non-blocking mode s.set_blocking(False) chan = s.open_session() while chan == LIBSSH2_ERROR_EAGAIN: print("Would block on session open, waiting for socket to be ready") wait_socket(sock, s) chan = s.open_session() while chan.execute(args.cmd) == LIBSSH2_ERROR_EAGAIN: print("Would block on channel execute, waiting for socket to be ready") wait_socket(sock, s) while chan.wait_eof() == LIBSSH2_ERROR_EAGAIN: print("Waiting for command to finish") wait_socket(sock, s) size, data = chan.read() while size == LIBSSH2_ERROR_EAGAIN: print("Waiting to read data from channel") wait_socket(sock, s) size, data = chan.read() while size > 0: print(data) size, data = chan.read()
def _init(self, retries=1): self.session = Session() if self.timeout: # libssh2 timeout is in ms self.session.set_timeout(self.timeout * 1000) try: self.session.handshake(self.sock) except Exception as ex: while retries < self.num_retries: return self._connect_init_retry(retries) msg = "Error connecting to host %s:%s - %s" logger.error(msg, self.host, self.port, ex) if isinstance(ex, SSH2Timeout): raise Timeout(msg, self.host, self.port, ex) ex.host = self.host ex.port = self.port raise try: self.auth() except Exception as ex: while retries < self.num_retries: return self._connect_init_retry(retries) msg = "Authentication error while connecting to %s:%s - %s" raise AuthenticationException(msg, self.host, self.port, ex) self.session.set_blocking(0) if self.keepalive_seconds: self.configure_keepalive() self._keepalive_greenlet = self.spawn_send_keepalive()
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 connect(self, privatekey_file="~/.ssh/id_rsa", passphrase='', open_channel=True): """Connect active host and open a session Args: privatekey_file: a string representing the path to the private key file passphrase: a string representing the password open_channel: if `True`, open the SSH channel Returns: None """ privatekey_file = os.path.expanduser(privatekey_file) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.active_host[2], self.active_host[3])) s = Session() s.handshake(sock) try: # Try using private key file first s.userauth_publickey_fromfile(self.active_host[1], privatekey_file, passphrase) except: # Use password to auth passwd = getpass( 'No private key found.\nEnter your password for %s: ' % self.active_host[1]) s.userauth_password(self.active_host[1], passwd) self.session = s if open_channel: self.channel = self.session.open_session() return
def make_ssh_session(sock: socket.socket, retry_count: int = 3, use_keepalive: bool = True) -> Session: """Create ssh session from existing socket :param sock: Socket to use for SSH session. :param retry_count: Count of max handshake retries. By default is set to 3. :param HandShakeFailedError: If ssh handshake fails. :return: SSH Session.""" ssh: Session = Session() ssh.set_blocking(True) if use_keepalive: ssh.keepalive_config(True, 3) for i in range(1, 3 + 1): try: ssh.handshake(sock) break except ssh2.exceptions.KeyExchangeError as exc: if i < retry_count: continue raise excs.HandShakeFailedError("SSH handshake failed") from exc except (ssh2.exceptions.SocketDisconnectError, ssh2.exceptions.SocketRecvError, ssh2.exceptions.SocketSendError) as exc: raise excs.HandShakeFailedError( "Connection seems to be closed by remote host") from exc return ssh
def main(): print('asdfasdf') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('reports.paypal.com', 22)) s = Session() s.handshake(sock) s.userauth_password(USERID, PASSWORD) chan = s.open_session() print('connected') sftp = s.sftp_init() print('sftp done') now = datetime.now() outf = open(RESULTFILE, "w+") filelist = getNames(YEAR, MONTH) with open(FILEOUT, 'w+') as f: for fileName in filelist: with sftp.open('/pptransfers/outgoing/' + fileName, LIBSSH2_FXF_READ, LIBSSH2_SFTP_S_IRUSR) as fh: print('sftp done') for size, data in fh: f.write(data) f.close() f = open(FILEOUT, 'r') for row in f: if row.startswith("SB") or row.startswith('"SB'): outf.write(row) outf.close() print("Finished file read in %s" % (datetime.now() - now, )) f.close()
def create_new_whm_account(domain_name): # generate password new_pass = password_generator.generate(length=15) # open connection sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('your_hostname', 'port_number_integer_remove_brackets')) session = Session() session.startup(sock) session.userauth_password('root', 'your_password') chanel = session.open_session() # form a 8-letter username username_whm_account = '' for char_letter in domain_name: if char_letter.isalpha(): username_whm_account += char_letter username_whm_account = username_whm_account[:8] # check if username and domain name already exist on the server chanel.execute( f'cd /var/cpanel/users; grep -r {domain_name}; grep -r {username_whm_account}' ) size, data = chanel.read() while (size > 0): # convert byte output to string datada = str(data.decode('ascii')) print(datada) size, data = chanel.read() if (f'DNS={domain_name}' in datada): print( f'Domain name {domain_name} already exists! Account creation failed! Aborting...' ) return 0 else: while (f'USER={username_whm_account}' in datada): print(f'Account name already exists! Creating new username!') username_whm_account = generate_new_account_name( username_whm_account) print(username_whm_account) chanel.close() chanel = session.open_session() chanel.execute( f'whmapi1 createacct username={username_whm_account} domain={domain_name} password={new_pass}' ) print(f'Account created! Here are the details:' f'username = {username_whm_account} ' f'password = {new_pass} ' f'domain name = {domain_name} ')
def setUp(self): self.host = '127.0.0.1' self.port = 2222 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) self.sock = sock self.session = Session() self.session.handshake(self.sock)
def test_bad_set_flag(self): failed = False self.session = Session() try: self.session.flag(LIBSSH2_METHOD_COMP_CS, 7) except ssh2_exceptions.MethodNotSupported: failed = True assert failed == True
def test_bad_internal_methods(self): failed = False self.session = Session() try: self.session.flag(LIBSSH2_FLAG_COMPRESS, True) self.session.methods(2222) except ssh2_exceptions.MethodNotSupported: failed = True assert failed == True
def test_bad_supported_algs(self): failed = False self.session = Session() self.session.flag(LIBSSH2_FLAG_COMPRESS, True) try: self.session.supported_algs(LIBSSH2_METHOD_COMP_CS, None) except ssh2_exceptions.MethodNotSupported: failed = True assert failed == True
def ssh_login3(user): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, port)) sock.setblocking(1) session = Session() session.handshake(sock) try: session.userauth_password(user, '123456') except AuthenticationError: return print(user)
def test_bad_method_pref(self): failed = False self.session = Session() perferences = {LIBSSH2_METHOD_HOSTKEY: b'blah'} try: self.set_method_preferences(perferences) self.session.handshake(self.sock) except ssh2_exceptions.MethodNotSupported: failed = True except Exception as e: print(e) assert failed == True
def _make_session(self) -> Session: """Makes SSH connection and handshake. Returns: Session: Succesfully connected Session object. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = Session() session.handshake(sock) session.userauth_publickey_fromfile(self.user, self.key) return session
def start_session(self, hostname, username): sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.connect((hostname, 22)) s = Session() s.handshake(sock) auth_methods = s.userauth_list(username) if 'publickey' in auth_methods: s.agent_auth(username) return s else: # print("Available authentiation methods: %s" % auth_methods) sys.exit("Only publickey is supported now!")