コード例 #1
1
ファイル: asuh.py プロジェクト: bluedaemon/ASUH
transport = paramiko.Transport((host,port))
transport.connect(username=user_,password=pass_)
sftp = paramiko.SFTPClient.from_transport(transport)

#download
#filepath = ''
#localpath= ''
#sftp.get(filepath,localpath)

#upload
#serverpath = ''
#localpath= ''
#sftp.put(serverpath,localpath)


chan = ssh_client.invoke_shell()
stdin = chan.makefile('wb')
stdout = chan.makefile('rb')

#for testing
#stdin.write('mkdir c')

filepaths=['c/fileio.c', 'c/fileio.h', 'c/min.c', 'c/max.c', 'c/rand.c']
#for i in filepaths:
#	sftp.put(i, i)
sftp.mkdir("c")
sftp.put('c/fileio.c','c/fileio.c')
sftp.put('c/fileio.h','c/fileio.h')
sftp.put('c/min.c','c/min.c')
sftp.put('c/max.c','c/max.c')
sftp.put('c/rand.c','c/rand.c')
コード例 #2
0
    def connect(self, host, username, password="", port=""):
        try:
            client = SSHClient()
            client.load_system_host_keys()
            client.set_missing_host_key_policy(AutoAddPolicy())

            client.connect(
                host,
                username=username,
                password=password,
                look_for_keys=True,
                timeout=5000,
            )

            self.channel = client.invoke_shell()

            detectedDevice = (self.channel.recv(len(self.deviceHostname) +
                                                2).decode().strip())
            if detectedDevice != "{0} #".format(
                    self.deviceHostname) and detectedDevice != "{0} $".format(
                        self.deviceHostname):
                self.error = (
                    "Device detected name does not match the device name provided."
                )
                self.disconnect
                return None
            return client
        except Exception as e:
            self.error = e
            return None
コード例 #3
0
ファイル: oxe_voicemail.py プロジェクト: fgadot/pyoxe
def vm_create_eva_access(host, port=22, password='******', accesses=15):
    """Summary
    
    Args:
        host (TYPE): Description
        port (int, optional): Description
        password (str, optional): Description
        accesses (int, optional): Description
    """
    data = 'NB_LINES=' + accesses
    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))
    channel = client.invoke_shell()
    while channel.recv_ready() is False:
        sleep(3)  # OXE is really slow on mtcl connexion
    stdout = channel.recv(4096)
    channel.send('cat >> /usr3/mao/eva.access << EOF\n' + data + '\nEOF\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    # print(stdout.decode(encoding='UTF-8'))
    channel.close()
    client.close()
コード例 #4
0
ファイル: oxe_netadmin.py プロジェクト: fgadot/pyoxe
def oxe_netdata_get(host, pattern, port=22, password='******'):
    """Summary
    
    Args:
        host (TYPE): Description
        pattern (TYPE): Description
        port (int, optional): Description
        password (str, optional): Description
    
    Returns:
        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))
    # stdout, stdin, stderr = client.exec_command('sed -n -e \'s/^' + pattern + '=\([^;][^;]*\).*/\\1/p\'  -e \'s/.*;' +
    #                                            pattern + '=\([^;][^;]*\).*/\\1/p\' /usr/netadm/data/netdata\n')
    channel = client.invoke_shell()
    while channel.recv_ready() is False:
        sleep(3)  # OXE is really slow on mtcl connexion
    stdout = channel.recv(4096)
    channel.send('cat /usr/netadm/data/netdata\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout = channel.recv(4096)
    channel.close()
    client.close()
    find = compile(pattern + '=.*').findall(
        stdout.decode('utf-8'))[0].split('=')[1]
    return find
コード例 #5
0
def oxe_reboot(host, port, password, swinst_password):
    """Reboot OXE Call Server
    
    Args:
        host (TYPE): Description
        port (TYPE): Description
        password (TYPE): Description
        swinst_password (TYPE): Description
    """
    # connect OXE through SSH and execute 'rainbowagent -v'
    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))
    channel = client.invoke_shell()
    while channel.recv_ready() is False:
        sleep(3)  # OXE is really slow on mtcl connexion
    stdout = channel.recv(4096)
    channel.send('reboot\n')
    while channel.recv_ready() is False:
        sleep(1)
    stdout += channel.recv(1024)
    channel.send(swinst_password + '\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    # pprint.pprint(stdout)
    channel.close()
    client.close()
コード例 #6
0
ファイル: MetIntegrationControl.py プロジェクト: jerkos/metms
 def startConnection(self): 
     """
     connection to remote server
     can launch a thread checking every minute your mailbox...
     """
     #if not self.directory:return
     #self.parent().close()
     self.close()
     client = SSHClient()
     client.set_missing_host_key_policy(AutoAddPolicy())
     try:
         client.connect(str(self.host.text()), username=str(self.username.text()), password=str(self.password.text()))
     except SSHException: qApp.instance().showErrorMessage("Error", "The ssh session could not be established")
     except AuthenticationException: qApp.instance().showErrorMessage("Error","Authentication failed")
     except BadHostKeyException: qApp.instance().showErrorMessage("Error", "the server's host key could not be verified")
     
     sftpCp = self.cleaningRepository(client)
     if sftpCp:
         sftp = client.open_sftp()
         self.sftpCopying(sftp)
         sftp.close()
     else:
         self.retrieveDirTree(c, out)
     self.makeRScript(client)
     self.makeShellScript(client)
     if self.interactiveSession.isChecked():
         import interactive
         print ('invoking a shell')
         chan = client.invoke_shell()
         chan.send('bash\n')
         interactive.interactive_shell(chan)
         chan.close()
     else:
         self.launchCommand(client)
     client.close()
コード例 #7
0
ファイル: router.py プロジェクト: LuisG93/router_test
def update_router():
    for router in request.json["routers"]:
        ssh = SSHClient()
        ssh.set_missing_host_key_policy(AutoAddPolicy())
        ssh.connect(router["ip"], router["port"], router["user"],
                    router["password"])
        ssh_command = ssh.invoke_shell()
        ssh_command.send("configure terminal\n")
        ssh_command.send("interface {}\n".format(router["interface"]))
        time.sleep(1)
        # output = ssh_command.recv(5000)
        # print(output)
        ssh_command.send("bandwidth {}\n".format(request.json["bandwidh"]))
        time.sleep(1)
        # output = ssh_command.recv(5000)
        # print(output)
        ssh_command.send("no shutdown\n")
        time.sleep(1)
        # output = ssh_command.recv(5000)
        # print(output)
        ssh_command.send("exit\n")
        ssh_command.send("exit\n")
        time.sleep(1)
        # output = ssh_command.recv(5000)
        # print(output)
        # ssh_command.send("copy running-config startup-config\n")
        ssh.close()
    return make_response({"message": "complete"})
コード例 #8
0
ファイル: remote_mount_safe.py プロジェクト: Fisk24/Safe
class Main():
    def __init__(self):
        self.server = "192.168.1.250"
        self.user   = "******"
        self.pw     = getpass.getpass("Password for \"fisk\" on the remote host:")
        self.initSSH("ask")
        self.execRemoteMount()
        input("Check volume mount then press enter")
        self.execRemoteClose()
        self.ssh.close()

    def sendData(self, data):
        while not self.channel.send_ready(): time.sleep(1)
        self.channel.send(str(data))

    def recvData(self, size):
        while not self.channel.recv_ready(): time.sleep(1)
        data = self.channel.recv(size)
        return data

    def execRemoteClose(self):
        stdin, stdout, stderr = self.ssh.exec_command("sudo /home/fisk/Projects/sshs/sshs close")

    def execRemoteMount(self):
        stdin, stdout, stderr = self.ssh.exec_command("sudo /home/fisk/Projects/sshs/sshs open /media/fisk/ARCHIVE1/Safe/onOLEcNsojuin.bin --key /media/fisk/ARCHIVE1/safe.keyfile")
        output = stdout.readlines()
        print(output)
        
    def initSSH(self, auto_add="no"):
        self.ssh = SSHClient() 
        self.ssh.set_missing_host_key_policy(AutoAddPolicy())
        self.ssh.connect(self.server, username=self.user, password=self.pw)
        self.channel = self.ssh.invoke_shell()
コード例 #9
0
ファイル: http2cli.py プロジェクト: jajalcoding/ruparupa
def ssh_cli_command(ipadd, user, pwd, namafile):
    client = SSHClient()
    client.set_missing_host_key_policy(AutoAddPolicy())
    try:
        client.connect(ipadd, username=user, password=pwd)
        remote_shell = client.invoke_shell()

    except AuthenticationException:
        print("Authentication failed, please verify your credentials !")
        return False
    except SSHException as sshException:
        print("Unable to establish SSH connection: %s" % sshException)
        return False
    except socket.error:
        print("Unable to connect to host " + ipadd)
        return False

    try:
        f = open(namafile, "r")
    except:
        print("File " + namafile + " is not found !")
        return False

    for line in f:
        if (len(line) > 1):
            remote_shell.send(line.strip() + "\n")
            while not remote_shell.recv_ready():
                time.sleep(.1)
            output = remote_shell.recv(10000)
            print(output.decode("ascii"))

    f.close()

    client.close()
    return True
コード例 #10
0
class SSHEngine(BaseTransportEngine):
    def __init__(self, hostname, username, password, timeout=.5):
        self._client = SSHClient()
        self._client.set_missing_host_key_policy(AutoAddPolicy())
        self._client.connect(hostname, username=username, password=password)
        self._shell = self._client.invoke_shell()
        self._shell.settimeout(timeout)
        self.send_command_get_output(' ')

    def _send_command(self, command, end):
        self._shell.send(command + end)

    def _get_output(self, buffer_size, return_as_list):
        data = ''
        while True:
            try:
                data += bytes.decode(self._shell.recv(buffer_size))
            except SocketTimeout:
                break

        if return_as_list:
            return data.splitlines()
        else:
            return data

    def close_connection(self):
        self._client.close()
コード例 #11
0
ファイル: pyios.py プロジェクト: bkranendonk/PyIOS
    def ssh_cfg(self,
                host,
                username,
                password,
                port=22,
                ignore_confirmation=False):
        if ignore_confirmation is not True:
            print(self.__repr__())
            self.print_cfg()
            print("\n")
            confirm = input("Type 'APPLY' to confirm configuration apply")
            if confirm != "APPLY":
                print("Not applying configuration.")
                return None
        cmd_list = self.export_cfg(remove_indent=True)

        # Do actual apply
        client = SSHClient()
        client.set_missing_host_key_policy(AutoAddPolicy())

        # Make connection and create shell.
        client.connect(host, port, username, password)
        shell = client.invoke_shell()
        for cmd in cmd_list:
            _, stdout, stderr = client.exec_command(cmd)
            print("== {} ==:\n{}{}".format(cmd, stdout, stderr))
            print("\n")
        print("\n")
        print("Applied configuration via SSH.")
コード例 #12
0
 def Start_Async_Show(self, host, user, passwd):
   ssh = SSHClient()
   ssh.load_system_host_keys()
   ssh.set_missing_host_key_policy(client.AutoAddPolicy())
   ssh.connect(host, port=22, username=user, password=passwd, timeout=30)
   channel = ssh.invoke_shell()
   channel.exec_command("show router bgp routes | match Routes")
   ssh.close()
コード例 #13
0
ファイル: deploythread.py プロジェクト: jehc/ros_ide
    def run(self):
        try:
            # run a command and wait for it to finish
            def run(command):
                _, stdout, _ = ssh.exec_command(command)
                stdout.channel.recv_exit_status()

            # send the webapp a textual progress update
            listener = Listener()
            def log(text):
                listener.publish(('project', self.project.name, 'deploy', 'status'), { 'text': text })

            # prevent accidentally deploying on the server itself
            # (this doesn't prevent deploying to the server's public
            # IP address, so there's still a security problem here)
            if self.host in ['127.0.0.1', '0.0.0.0']:
                raise Exception('you\'re trying to deploy to the server!')

            # create temporary build file
            path = os.path.join(tempfile.mkdtemp(), 'deploy.launch')
            xml = roslaunch_xml_for_file(self.project.project_file_path, self.remote_deploy_path)
            open(path, 'w').write(xml)
            log('Created file: deploy.launch')

            # create a ssh session
            log('Connecting to %s@%s...' % (self.user, self.host))
            ssh = SSHClient()
            ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(AutoAddPolicy())
            ssh.connect(self.host, username=self.user, password=self.password)
            log('Connected to remote machine')

            # clean the deploy location
            run('rm -fr %s' % self.remote_deploy_path)
            run('mkdir -p %s' % self.remote_deploy_path)
            log('Cleaned deploy location')

            # copy the launch file over
            scp = SCPClient(ssh.get_transport())
            scp.put(path, remote_path=self.remote_deploy_path)
            log('Copied file: deploy.launch')

            # run the file
            command = 'cd %s && roslaunch deploy.launch' % self.remote_deploy_path
            channel = ssh.invoke_shell()
            channel.send(command + '\nexit\n')
            log('Ran command: roslaunch deploy.launch')

            # wait for the command to finish
            import time
            while not self.die:
                time.sleep(0.1)
        except:
            import traceback
            log('Exception:\n' + traceback.format_exc())

        ssh.close()
        log('Connection was closed')
コード例 #14
0
ファイル: __init__.py プロジェクト: Simple2B/mdm-port
class SshShell(object):
    class Error(Exception):
        def __init__(self, message: str):
            self.message = message

    def __init__(self, host, user, passwd=None, port=22):
        self.client = SSHClient()
        self.client.set_missing_host_key_policy(AutoAddPolicy())
        self.client.connect(
            host,
            port=port,
            username=user,
            password=passwd,
        )

    def exec_command(self, cmd: str):
        log(log.DEBUG, "RemoteShell: command [%s]", cmd)
        if not self.client:
            return None
        stdin, stdout, stderr = self.client.exec_command(cmd)
        error_lines = stderr.readlines()
        if error_lines:
            log(log.ERROR, "RemoteShell: error exec command [%s]", cmd)
            error_message = "\n".join(
                [line.strip("\n\r") for line in error_lines])
            raise RemoteShell.Error(error_message)
        result = "\n".join([line.strip("\n\r") for line in stdout.readlines()])
        log(log.DEBUG, "RemoteShell: result [%s]", result)
        return result

    def send_command(self, cmd):
        log(log.DEBUG, "RemoteShell: command [%s]", cmd)
        BUFFER_SIZE = 1024
        with self.client.get_transport().open_session() as channel:
            channel.get_pty(width=1024)
            channel.settimeout(5)
            channel.exec_command(cmd + "\n")
            if channel.recv_stderr_ready():
                log(log.ERROR, "RemoteShell: Error")
                data = channel.recv_stderr(BUFFER_SIZE)
                error_message = data.decode()
                raise RemoteShell.Error(error_message)
            out_message = ""
            while True:
                data = channel.recv(BUFFER_SIZE)
                if not data:
                    break
                out_message += data.decode()
            return out_message

    def run_shell_command(self, cmd):
        with self.client.invoke_shell() as chan:
            while chan.recv_ready():
                time.sleep(1)
                chan.recv(1024)
            time.sleep(1)
            chan.send(f"{cmd}\n")
            return chan.recv(1024).decode()
コード例 #15
0
class SSHConnection:
    attrs = "open", "get", "put", "chmod", "exec_command", "mkdir", "rmdir"

    def __init__(self, hostname, username, password, queue):
        self.hostname, self.username, self.password = hostname, username, password
        self.queue = queue

        from paramiko import SSHClient, AutoAddPolicy
        self.client = SSHClient()
        self.client.set_missing_host_key_policy(AutoAddPolicy())

    def __enter__(self):
        self.client.connect(hostname=self.hostname,
                            username=self.username,
                            password=self.password)

        self.channel = self.client.invoke_shell()
        self.stdin = self.channel.makefile("w")
        self.stdout = self.channel.makefile("r")
        self.stderr = self.channel.makefile_stderr("r")
        self.output_thread = Thread(target=self.output)
        self.error_thread = Thread(target=self.error)
        self.output_thread.start()
        self.error_thread.start()
        self.sftp_client = self.client.open_sftp()

        return self

    def __getattr__(self, attr):
        if attr not in self.attrs:
            raise AttributeError(
                f"'{self.__class__}' object has no attribute '{attr}'")

        elif hasattr(self.sftp_client, attr):
            return getattr(self.sftp_client, attr)
        elif hasattr(self.client, attr):
            return getattr(self.client, attr)

    def __exit__(self, et, ev, tb):
        self.sftp_client.close()
        self.stdout.close()
        self.stderr.close()
        self.stdin.close()
        self.channel.close()
        self.client.close()

    def exec(self, command):
        self.stdin.write(command + "\n")

    def output(self):
        for line in self.stdout:
            self.queue.put(self.hostname, "stdout", line)

    def error(self):
        for line in self.stderr:
            self.queue.put(self.hostname, "stderr", line)
コード例 #16
0
def searchTopology(devices):
    for device in devices:
        connection = SSHClient()
        connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        connection.connect(device,
                           username=username,
                           password=password,
                           look_for_keys=False,
                           allow_agent=False)
        new_connection = connection.invoke_shell()
        output = clear_buffer(new_connection)
        time.sleep(2)
        new_connection.send("terminal length 0\n")
        output = clear_buffer(new_connection)
        try:
            router = output.decode('utf-8')
        except:
            print('The router interface is down')
            new_connection.close()
            continue
        router = router[2:4]
        # If the router is already in the list of routers, close the ssh connection
        if router in routers:
            print(f'The router {router} is already visited')
            new_connection.close()
            continue
        # Retrieving the routing table
        new_connection.send(route_table)
        time.sleep(2)
        table = new_connection.recv(max_buffer).decode('utf-8')
        routes, routers[router] = getNetworksDirectlyConnected(table)
        # Filtering the obtained list
        dispositivos = [
            route.replace('252', '253') for route in routes
            if route.endswith('.252')
        ]
        for dispositivo in dispositivos:
            print(
                f'Obtaining the devices that are directly connected to this router: {dispositivo}'
            )
            new_connection.send(f'ssh -l {username} {dispositivo} \n')
            time.sleep(2)
            new_connection.send(f'{password}\n')
            time.sleep(2)
            new_connection.send(route_table)
            time.sleep(2)
            # Obtaining the routing table for every single router
            table = new_connection.recv(max_buffer).decode('utf-8')
            router = table[-3] + table[-2]
            _, routers[router] = getNetworksDirectlyConnected(table)
            new_connection.send('exit\n')
            time.sleep(2)

        # Closing the ssh connection
        new_connection.close()
コード例 #17
0
def describeInterface(hostname):
    if hostname == 'R4':
        print("Setting up the routing table for Router 4...")
        connection = SSHClient()
        connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        connection.connect(gateway,
                           username=username,
                           password=password,
                           look_for_keys=False,
                           allow_agent=False)
        new_connection = connection.invoke_shell()
        time.sleep(2)
        new_connection.send('terminal length 0\n')
        print(f'Obtaining the {hostname} router information\n')
        router_info = getNetworsRouter(hostname, routers)
        print(router_info)
        # Executing the commands for setting up the routing table
        new_connection.send('conf t\n')
        time.sleep(2)
        new_connection.send('router ospf 1\n')
        time.sleep(2)
        id_network_R3 = router_info['R3'][1]
        new_connection.send(f'network { id_network_R3 } 0.0.0.255 area 0\n')
        time.sleep(2)
        new_connection.send('redistribute rip metric 200 subnets\n')
        time.sleep(2)
        new_connection.send('redistribute static metric 200 subnets\n')
        time.sleep(2)
        new_connection.send('exit\n')
        time.sleep(2)
        new_connection.send('router rip\n')
        time.sleep(2)
        new_connection.send('version 2\n')
        time.sleep(2)
        new_connection.send('redistribute static\n')
        time.sleep(2)
        new_connection.send('redistribute ospf 1\n')
        time.sleep(2)
        new_connection.send('no auto-summary\n')
        time.sleep(2)
        id_network_R2 = router_info['R2'][1]
        new_connection.send(f'network {id_network_R2}\n')
        time.sleep(2)
        new_connection.send('exit\n')
        time.sleep(2)
        network_R1 = router_info['R1']
        new_connection.send(
            f'ip route 10.0.5.0 255.255.255.0 {network_R1[0]}\n')
        time.sleep(2)
        # Closing the ssh connection
        new_connection.close()

    return jsonify(Router=hostname,
                   Devices_Directly_Connected=routers[hostname])
コード例 #18
0
ファイル: oxe_netadmin.py プロジェクト: fgadot/pyoxe
def oxe_netdata_update(host,
                       data,
                       port=22,
                       password='******',
                       root_password='******'):
    """Summary
    
    Args:
        host (TYPE): Description
        data (TYPE): Description
        port (int, optional): Description
        password (str, optional): Description
        root_password (str, optional): 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))
    channel = client.invoke_shell()
    while channel.recv_ready() is False:
        sleep(3)  # OXE is really slow on mtcl connexion
    stdout = channel.recv(4096)
    channel.send('su -\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    channel.send(root_password + '\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    channel.send('cat >> /usr/netadm/data/netdata << EOF\n' + data + '\nEOF\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    channel.send('netadmin -c\n')
    while channel.recv_ready() is False:
        sleep(2)
    stdout += channel.recv(1024)
    channel.send('chmod 664 /usr/netadm/data/netdata\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    # print(stdout.decode(encoding='UTF-8'))
    channel.close()
    client.close()
コード例 #19
0
ファイル: oxe_access.py プロジェクト: fgadot/pyoxe
def oxe_wbm_update_requests_quota(host,
                                  port,
                                  password,
                                  root_password,
                                  new_limit=50):
    """Update WBM requests limit for configuration zone (not authentication zone)
    
    Args:
        host (STR): OmniPCX Enterprise IP address
        port (INT): SSH port
        password (STR): mtcl password
        root_password (TYPE): root password
        new_limit (int, optional): Description
    """

    # Build OXE sed command
    cmd = 'sed -i -e \'s/zone=two\:1m rate\=2r\/s/zone=two\:1m rate\=' + new_limit + \
          'r\/s/g\' /usr/local/openresty/nginx/conf/wbm.conf\n'

    # SSH connection
    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))
    channel = client.invoke_shell()
    while channel.recv_ready() is False:
        sleep(
            3
        )  # OXE is really slow on mtcl connexion (Update this timer on physical servers)
    stdout = channel.recv(4096)
    channel.send('su -\n')
    while channel.recv_ready() is False:
        sleep(1)
    stdout += channel.recv(1024)
    channel.send(root_password + '\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    # channel.send('sed -i -e \'s/zone=two\:1m rate\=2r\/s/zone=two\:1m rate\=50r\/s/g\' /usr/local/openresty/nginx/conf/wbm.conf\n')
    channel.send(cmd)
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    channel.close()
    client.close()
コード例 #20
0
	def _fetch_probsup_dump(self, ap):
		client = SSHClient()
		client.set_missing_host_key_policy(AutoAddPolicy())
		try:
			client.connect(hostname=ap["ip_address"], port=ap["ssh_port"],
				           username=ap["login"], password=ap["password"], timeout=3)
		except (NoValidConnectionsError, timeout):
			return ""
		connect = client.invoke_shell()
		connect.send("wl -i %s probsup_dump\n" % ap["monitoring_interface"])
		while not connect.recv_ready():
			sleep(0.1)
		probsup_dump = connect.recv(50000).decode()
		connect.close()
		client.close()
		return probsup_dump
コード例 #21
0
ファイル: scan.py プロジェクト: cvvnx1/sliceVA
 def run(self, hostname, username, password):
     if self.commands.__len__() == 0: return False
     method = Device.objects.filter(host=hostname)[0].loginmethod
     if method == "ssh":
         ssh = SSHClient()
         ssh.set_missing_host_key_policy(AutoAddPolicy())
         try:
             ssh.connect(hostname=hostname, username=username, password=password, timeout=2)
         except:
             return False
         shell = ssh.invoke_shell()
         shell.send('config terminal' + '\r\n')
         for command in self.commands:
             shell.send(command + '\r\n')
             sleep(0.5)
         return True
     elif method == "telnet":
         pass
コード例 #22
0
def Hostname_Updater(ipaddr, username='******', password='******'):
    remote_conn_pre = SSHClient()
    remote_conn_pre.set_missing_host_key_policy(AutoAddPolicy())
    remote_conn_pre.connect(ipaddr,
                            username=username,
                            password=password,
                            look_for_keys=False,
                            allow_agent=False)
    print "...Connection established on {}...".format(ipaddr)
    remote_conn = remote_conn_pre.invoke_shell()
    output = remote_conn.recv(1000)
    print output
    remote_conn.send("terminal length 0\renable\rcisco\rconf t\r")
    hostname = raw_input("New hostname: ")
    time.sleep(0.5)
    remote_conn.send("hostname {}\r".format(hostname))
    print "Hostname successfully updated to {}".format(hostname)
    remote_conn_pre.close()
コード例 #23
0
ファイル: lab1.py プロジェクト: raphsls/IPWSP
def SSH_Connect():
    remote_conn_pre = SSHClient()
    remote_conn_pre.set_missing_host_key_policy(AutoAddPolicy())
    remote_conn_pre.connect(ipaddr,
                            username=username,
                            password=password,
                            look_for_keys=False,
                            allow_agent=False)
    remote_conn = remote_conn_pre.invoke_shell()
    print "Interactive SSH session established"
    output = remote_conn.recv(1000)
    print output
    remote_conn.send('terminal length 0\renable\rconf t')
    hostname = raw_input("Would would you like to change the hostname to: ")
    remote_conn.send("hostname {}\r".format(hostname))
    time.sleep(2)
    print "Hostname successfully changed {}".format(hostname)
    remote_conn_pre.close()
コード例 #24
0
ファイル: MetIntegrationControl.py プロジェクト: jerkos/metms
    def startConnection(self):
        """
        connection to remote server
        can launch a thread checking every minute your mailbox...
        """
        #if not self.directory:return
        #self.parent().close()
        self.close()
        client = SSHClient()
        client.set_missing_host_key_policy(AutoAddPolicy())
        try:
            client.connect(str(self.host.text()),
                           username=str(self.username.text()),
                           password=str(self.password.text()))
        except SSHException:
            qApp.instance().showErrorMessage(
                "Error", "The ssh session could not be established")
        except AuthenticationException:
            qApp.instance().showErrorMessage("Error", "Authentication failed")
        except BadHostKeyException:
            qApp.instance().showErrorMessage(
                "Error", "the server's host key could not be verified")

        sftpCp = self.cleaningRepository(client)
        if sftpCp:
            sftp = client.open_sftp()
            self.sftpCopying(sftp)
            sftp.close()
        else:
            self.retrieveDirTree(c, out)
        self.makeRScript(client)
        self.makeShellScript(client)
        if self.interactiveSession.isChecked():
            import interactive
            print('invoking a shell')
            chan = client.invoke_shell()
            chan.send('bash\n')
            interactive.interactive_shell(chan)
            chan.close()
        else:
            self.launchCommand(client)
        client.close()
コード例 #25
0
async def accept(websocket, path):
    dataline = ""

    #  ssh
    client = SSHClient()
    client.set_missing_host_key_policy(AutoAddPolicy())
    client.connect(hostname='ip address',
                   username='******',
                   password='******',
                   port=22)
    channel = client.invoke_shell()
    while not channel.recv_ready():
        time.sleep(0.1)
    buff = ''
    resp = channel.recv(9999).decode('utf-8')
    buff += resp
    print(resp)
    # login message
    dataline = resp

    def send_command(cmd):
        buff = ''
        while not buff.endswith(']# '):
            channel.send(cmd + '\n')
            resp = channel.recv(9999).decode('utf-8')
            buff += resp
            return str(resp)

    while True:
        # クライアントからメッセージ待機
        data = await websocket.recv()

        if data == "send":
            # クライアントに送信
            dataline = send_command(dataline)
            await websocket.send(dataline)
            data = ""
            dataline = ""
        dataline = dataline + data
        print("received: " + data)
        print("dataline: " + dataline)
コード例 #26
0
 def run(self, hostname, username, password):
     if self.commands.__len__() == 0: return False
     method = Device.objects.filter(host=hostname)[0].loginmethod
     if method == "ssh":
         ssh = SSHClient()
         ssh.set_missing_host_key_policy(AutoAddPolicy())
         try:
             ssh.connect(hostname=hostname,
                         username=username,
                         password=password,
                         timeout=2)
         except:
             return False
         shell = ssh.invoke_shell()
         shell.send('config terminal' + '\r\n')
         for command in self.commands:
             shell.send(command + '\r\n')
             sleep(0.5)
         return True
     elif method == "telnet":
         pass
コード例 #27
0
ファイル: ssh_server_control.py プロジェクト: obiwandu/DCA
class SSHServerControl(AgentControl):
    """ Inherit from AgentControl. Implement all existing methods in the way of SSH.
    """
    def __init__(self):
        super(SSHServerControl, self).__init__()
        self.ssh = SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.shell = None

    def login(self, identity):
        try:
            self.ssh.connect(identity.ip, username=identity.dev_id, password=identity.dev_pw)
            self.shell = self.ssh.invoke_shell()
            buf = ''
            while not (buf.endswith('$ ') or buf.endswith('# ')):
                buf += self.shell.recv(9999)
            print buf
        except BadHostKeyException, e:
            print '%s' % e
        except AuthenticationException, e:
            print '%s' % e
コード例 #28
0
class ParamikoWrapper:
    def __init__(self, hostname, username, password):
        self.client = SSHClient()
        self.client.load_system_host_keys()

        # Research more meaningful exceptions to catch
        try:
            self.client.connect(hostname=hostname,
                                username=username,
                                password=password)
            self.client.connected = True
        except:
            self.client.connected = False
            return

        try:
            self.session = self.client.invoke_shell()
            self.session.setblocking(0)
            self.session.settimeout(.25)
        except:
            self.client.connected = False
            pass

    def send_input(self, input):
        self.session.send(input)

    def flush_output(self):
        out = ''
        while True:
            try:
                concat = self.session.recv(10000)
                out += concat
            except:
                return out

    def is_connected(self):
        return self.client.connected

    def __del__(self):
        self.client.close()
コード例 #29
0
ファイル: router.py プロジェクト: LuisG93/router_test
def get_router():
    response = {}
    for router in request.json["routers"]:
        try:
            ssh = SSHClient()
            ssh.set_missing_host_key_policy(AutoAddPolicy())
            ssh.connect(router["ip"], router["port"], router["user"],
                        router["password"])
        except Exception:
            response[router["ip"] + "_" +
                     router["interface"]] = "Connection error"
            ssh.close()
        else:
            ssh_command = ssh.invoke_shell()
            ssh_command.send("show interface {}\n".format(router["interface"]))
            time.sleep(2)
            output = ssh_command.recv(5000).decode()
            # Validate if interface exist
            if output.find("Invalid input detected at") < 0:
                extract_data = {}
                if "bandwidth" in request.json["info"]:
                    search = re.search(r'BW (.*?), ', output)
                    if search:
                        extract_data["bandwidth"] = search.group(1)
                    else:
                        extract_data["bandwidth"] = "bandwidth not found"
                if "address" in request.json["info"]:
                    search = re.search(r'Internet address is (.*?)\r\n',
                                       output)
                    if search:
                        extract_data["address"] = search.group(1)
                    else:
                        extract_data["address"] = "address not found"
                response[router["ip"] + "_" +
                         router["interface"]] = extract_data
            else:
                key = router["ip"] + "_" + router["interface"]
                response[key] = "Interface not found"
            ssh.close()
    return response
コード例 #30
0
ファイル: oxe_rainbow.py プロジェクト: fgadot/pyoxe
def oxe_purge_rainbowagent_logs(host,
                                port=22,
                                password='******',
                                root_password='******'):
    """Summary
    
    Args:
        host (TYPE): Description
        port (int, optional): Description
        password (str, optional): Description
        root_password (str, optional): 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))
    channel = client.invoke_shell()
    while channel.recv_ready() is False:
        sleep(3)  # OXE is really slow on mtcl connexion
    stdout = channel.recv(4096)
    channel.send('su -\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    channel.send(root_password + '\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    channel.send('rm -f /var/log/rainbowagent.log.*\n')
    while channel.recv_ready() is False:
        sleep(0.5)
    stdout += channel.recv(1024)
    # print(stdout.decode(encoding='UTF-8'))
    channel.close()
    client.close()
コード例 #31
0
ファイル: ssh_server_control.py プロジェクト: obiwandu/DCA
class SSHServerControl(AgentControl):
    """ Inherit from AgentControl. Implement all existing methods in the way of SSH.
    """
    def __init__(self):
        super(SSHServerControl, self).__init__()
        self.ssh = SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.shell = None

    def login(self, identity):
        try:
            self.ssh.connect(identity.ip,
                             username=identity.dev_id,
                             password=identity.dev_pw)
            self.shell = self.ssh.invoke_shell()
            buf = ''
            while not (buf.endswith('$ ') or buf.endswith('# ')):
                buf += self.shell.recv(9999)
            print buf
        except BadHostKeyException, e:
            print '%s' % e
        except AuthenticationException, e:
            print '%s' % e
コード例 #32
0
ファイル: utils.py プロジェクト: kgarmtz/ssh-topology-project
def registerSSHUser(username, password, router_address, flag=''):
    default_user = '******'
    default_pass = '******'
    commands = [
        'enable\n', 'config t\n',
        f'{flag} username {username} privilege 15 password {password}\n',
        'end\n'
    ]
    connection = SSHClient()
    connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    connection.connect(router_address,
                       username=default_user,
                       password=default_pass,
                       look_for_keys=False,
                       allow_agent=False)
    new_connection = connection.invoke_shell()
    output = clear_buffer(new_connection)
    time.sleep(wait)
    for command in commands:
        new_connection.send(command)
        time.sleep(wait)
    # Closing the ssh connection
    new_connection.close()
コード例 #33
0
ファイル: demo.py プロジェクト: bluedaemon/ASUH
if host_keys.has_key(host_):
    hostkeytype = host_keys[host_].keys()[0]
    hostkey = host_keys[host_][hostkeytype]
    print 'Using host key of type %s' % hostkeytype

ssh_client = SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=host_, username=user_, password=pass_)
#privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
#mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
t = paramiko.Transport((host_,port_))
t.connect(username=user_,password=pass_,hostkey=hostkey)
sftp = paramiko.SFTPClient.from_transport(t)

connection = ssh_client.invoke_shell()
stdin = connection.makefile('wb')
stdout = connection.makefile('rb')

dirlist = sftp.listdir('.')
print "DirList:", dirlist
filepaths = ['c/fileio.c', 'c/fileio.h', 'c/min.c', 'c/max.c', 'c/rand.c']
sftp.mkdir("c")
for i in filepaths:
	sftp.put(i,i)


stdin.write(
'''
cd
gcc -o ran c/fileio.h c/fileio.c c/rand.c
コード例 #34
0
ファイル: manager.py プロジェクト: arthur-bryan/pisco
class Manager:
    """ The class that holds the methods used to configure the devices. """

    CONFIG_FILE_PATH = os.path.join(os.path.dirname(__file__), 'data',
                                    'config.json')
    variables = {
        "DEVICE_HOSTNAME": None,
        "ENABLE_PASSWORD": None,
        "DOMAIN_NAME": None,
        "VLAN_NUMBER": None
    }
    keys = list(variables.keys(
    ))  # keywords that will be replaced if found on 'config.json' commands.
    configuration_keywords = ('DEFAULT_CONFIG', 'SET_HOSTNAME', "CREATE_VLAN",
                              'DELETE_VLAN', 'ACCESS_SSH_ONLY',
                              'ACCESS_TELNET_ONLY', 'ACCESS_SSH_TELNET',
                              'SHOW_INTERFACES_STATUS', 'SHOW_INTERFACES_IP')
    config_file = open(CONFIG_FILE_PATH, "r")
    config_json = json.load(config_file)

    def __init__(self):
        self.__devices = []
        self.__vlans_to_configure = None
        self.__obj_connect = None
        self.__shell = None

    def add_device(self, device):
        """ Add the device (obj) to the list of devices to be configured.

            Args:
                device (:obj: `Device`): The device to be added.

        """
        self.__devices.append(device)

    def configure_devices(self, *args):
        """ Starts the configuration of devices on the devices list. """
        for _, device in enumerate(self.__devices):
            self.variables['ENABLE_PASSWORD'] = device.enable_secret
            self.variables['DOMAIN_NAME'] = device.domain_name
            auxiliar_functions.clear()
            print(f"\n[ + ] CONFIGURING  THE {_+1}º DEVICE...\n")
            if len(args) < 1:
                print(
                    f"\n\n[ ! ] You must choose at least one configuration (see README or documentation)."
                )
                auxiliar_functions.close()
            if device.connection_protocol == "TELNET":
                try:
                    self.__login_over_telnet(device)
                    self.__configure(device, args)
                    self.__obj_connnect.close()
                except Exception as e:
                    print(f"\n\n{e}")
                    auxiliar_functions.close()
            else:
                try:
                    self.__login_over_ssh(device)
                    self.__configure(device, args)
                    self.__obj_connect.close()
                except Exception as e:
                    print(f"\n\n{e}")
                    auxiliar_functions.close()
        auxiliar_functions.close()

    @property
    def vlans_to_configure(self):
        return self.__vlans_to_configure

    @vlans_to_configure.setter
    def vlans_to_configure(self, vlans):
        self.__vlans_to_configure = vlans

    def __login_over_telnet(self, device):
        """ Creates an Telnet client object, then tries to login to the device using its attributes.

            Args:
                device (:obj: `Device`): The device that the manager will connect to.

        """
        try:
            self.__obj_connect = Telnet(device.ip_address, "23", 5)
            # self.obj_connect.set_debuglevel(1) # uncomment this line to enable debug for Telnet obj.
        except Exception as error:
            print(f"[ ! ] {error}.")
            auxiliar_functions.close()
        else:
            if device.vty_username != "":
                self.__obj_connect.read_until(b"Username:"******"\n")
                sleep(0.5)
            self.__obj_connect.read_until(b"Password:"******"\n")
            sleep(0.5)
            self.__identify_errors(device)
            self.__obj_connect.write(b"enable\n")
            self.__obj_connect.read_until(b"Password:"******"\n")
            sleep(0.5)
            self.__identify_errors(device)

    def __login_over_ssh(self, device):
        """ Creates an SSHClient object, load the keys, then tries to login to the device using its attributes.

            Args:
                device (:obj: `Device`): The device that the manager will connect to.

        """
        self.__obj_connect = SSHClient()
        self.__obj_connect.load_system_host_keys()
        self.__obj_connect.set_missing_host_key_policy(AutoAddPolicy())
        try:
            self.__obj_connect.connect(device.ip_address, 22,
                                       device.vty_username,
                                       device.vty_password)
            self.__shell = self.__obj_connect.invoke_shell(
            )  # Opens a shell to run commands.
        except Exception as error:
            print(f"[ ! ] {error}")
            self.__obj_connect.close()
            auxiliar_functions.close()
        else:
            self.__identify_errors(device)
            self.__shell.send(b"enable\n")
            sleep(0.5)
            self.__shell.send(device.enable_secret.encode() + b"\n")
            sleep(0.5)
            self.__identify_errors(device)

    def __configure(self, device, configurations):
        """ Start running commands on device if the configurations keys exists on 'config.json' file.

            Args:
                device (:obj: `Device`): The device to be configured.
                configurations (str): The command keys based on 'config.json'.

        """
        for config_key in configurations:
            if config_key in self.configuration_keywords:
                if config_key == 'SET_HOSTNAME':
                    variables["DEVICE_HOSTNAME"] = input("[->] Set hostname: ")
                    self.__send_commands(device, config_key)
                elif config_key == 'CREATE_VLAN' or config_key == 'DELETE_VLAN':
                    if self.__vlans_to_configure == None:
                        print(
                            "\n\n[ ! ] You must specify the VLANs to be configured!(see README or documentation.)"
                        )
                        auxiliar_functions.close()
                    for vlan in self.__vlans_to_configure:
                        if int(vlan) not in range(3968,
                                                  4048) and int(vlan) != 4094:
                            self.variables["VLAN_NUMBER"] = vlan
                            self.__send_commands(device, config_key)
                    self.variables["VLAN_NUMBER"] = self.vlans_to_configure[0]
                else:
                    self.__send_commands(device, config_key)
            else:
                print(
                    f"\n\n[ ! ] There is no valid configuration for '{config_key}'."
                )
                auxiliar_functions.close()

    def __send_commands(self, device, config_key):
        """ Run the commands on the device based on the choosen configuration keyword.

            Args:
                device (:obj: `Device`): The device that will receive the commands.
                config_key (int): The configuration key to run based on the 'config.json' file.

        """
        commands = list(self.config_json[config_key].values())[0]
        if device.connection_protocol == "SSH":
            for command in commands:
                found_key = list(filter(lambda key: key in command, self.keys))
                if len(found_key) > 0:
                    self.__shell.send(
                        command.replace(
                            found_key[0],
                            self.variables[found_key[0]]).encode('ascii'))
                    self.__identify_errors(device)
                    sleep(0.6)
                else:
                    self.__shell.send(command.encode())
                    self.__identify_errors(device)
                    sleep(0.6)
        else:
            for command in commands:
                found_key = list(
                    filter(lambda key: key in command,
                           self.keys))  # found commands to be replaced.
                if len(found_key) > 0:
                    self.__obj_connect.write(
                        command.replace(
                            found_key[0],
                            self.variables[found_key[0]]).encode('ascii'))
                    self.__identify_errors(device)
                    sleep(
                        0.6
                    )  # timeout before send another command to prevent errors.
                else:
                    self.__obj_connect.write(command.encode('ascii'))
                    self.__identify_errors(device)
                    sleep(0.6)

    def __identify_errors(self, device):
        """ Handle the command output to verify if there is errors based on a dict with some errors keywords
            and its descriptions.

            Args:
                device (:obj: `Device`): The current device being configurated.

        """
        def find_error_on_line(output_line):
            """ Verify if the output command line has errors based on a predefined dict.

                Args:
                    output_line (str): The device output command line to be verified.

            """
            found_error = list(
                filter(lambda error: error in output_line, errors_keywords))
            if len(found_error) > 0:
                print(f"[ ! ] {errors_dict[found_error[0]]}")
                auxiliar_functions.close()
            else:
                print(output_line, end='')

        errors_dict = {
            '% Login invalid':
            "\n\n[ ! ] Invalid VTY login credentials!",
            '% Bad passwords':
            "\n\n[ ! ] Invalid VTY password!",
            '% Bad secrets':
            "\n\n[ ! ] Invalid secret! Can't configure",
            '% No password set':
            "\n\n[ ! ] No enable password configured on device! Cant run scripts.",
            'Translating':
            "\n\n[ ! ] Username not configured on device. Set a username or leave it blank.",
            'number which is out of the range 1..4094':
            "\n\n[ ! ] Invalid vlan number!"
        }
        errors_keywords = [key for key in errors_dict]
        if device.connection_protocol == 'TELNET':
            errors_keywords = [key for key in errors_dict]
            line = self.__obj_connect.read_very_eager().decode('ascii')
            if '% Do you really want to replace them?' in line or '% You already have RSA keys defined' in line:
                self.__obj_connect.write(b'no\n')
            find_error_on_line(line)
        else:
            line = self.__shell.recv(65535).decode('ascii')
            if '% Do you really want to replace them?' in line or '% You already have RSA keys defined' in line:
                self.__shell.send(b'no\n')
            find_error_on_line(line)
コード例 #35
0
class SshConnector:
    host = ""
    user = ""
    ssh_config = None
    ssh_client = None
    batch_sys = None
    batch_config = None
    ssh_log = ""
    prompt = ""

    def __init__(self, host, home_path, batch_sys, user=None):
        self.batch_sys = Batchsystem()
        self.batch_sys.read_config()
        self.batch_config = self.batch_sys.get_batchsystem_config(batch_sys)
        if user is None:
            self.host = host
            self.read_ssh_config(host)
            self.connect_with_config()
        else:
            self.host = host
            self.user = user
            self.connect(host, user)
        self.detect_prompt(home_path)

    # connect to host with config
    def connect_with_config(self):
        self.ssh_client = SSHClient()
        self.ssh_client.load_system_host_keys()
        self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
        self.ssh_client.connect(self.ssh_config['hostname'],
                                username=self.ssh_config['user'])

    # connect with user parameter
    def connect(self, host, user):
        password = getpass.getpass()
        self.ssh_client = SSHClient()
        self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
        self.ssh_client.connect(host, username=user, password=password)

    # read ssh config of user
    def read_ssh_config(self, hostname):
        config_file = os.path.join(os.getenv('HOME'), '.ssh/config')
        config = SSHConfig()
        config.parse(open(config_file, 'r'))
        self.ssh_config = config.lookup(hostname)
        if len(self.ssh_config.keys()) < 2:
            print("Hostname no found in .ssh/config")

    #returns an session channel
    def create_session(self):
        return self.ssh_client.invoke_shell()

    # execute command on the host, blocking semantic
    def execute(self, cmd):
        ssh_stdin, ssh_stdout, ssh_stderr = self.ssh_client.exec_command(cmd)
        self.ssh_log += str(ssh_stderr.read())
        return str(ssh_stdout.read())

    # TODO implement own function to check prompt in reverse order
    def execute_in_session(self, cmd, channel):
        while not channel.send_ready():
            time.sleep(0.00001)
        channel.send(cmd + '\n')
        recv_buffer = " "
        while not recv_buffer.endswith(self.prompt + ' '):
            rsp = channel.recv(1024)
            recv_buffer += rsp
        pattern = self.prompt + ' ' + cmd
        begin = recv_buffer.find(pattern) + len(pattern) + 2
        end = len(recv_buffer) - len(self.prompt + ' ')
        return recv_buffer[begin:end]

    def detect_prompt(self, home_path):
        channel = self.ssh_client.invoke_shell()
        while not channel.send_ready():
            time.sleep(0.00001)
        channel.send('echo $HOME\n')
        recv_buffer = ''
        while not home_path in recv_buffer:
            resp = channel.recv(1024)
            recv_buffer += resp
        idx = recv_buffer.rfind('echo')
        prompt = ''
        for i in range(idx - 2, -1, -1):
            if(recv_buffer[i] == ' '):
                break
            elif(recv_buffer[i] != '\r' and recv_buffer[i] != '\n'
                                   and recv_buffer[i] != '\t'):
                prompt += recv_buffer[i]
        self.prompt = prompt[::-1]

    def print_log(self):
        print("\n\nSSH LOG")
        print("========")
        print(self.ssh_log)

    def print_modules(self):
        print(self.exec_command("module av"))

    def load_modules(self, modules, channel):
        return self.execute_in_session("module load {}".format(modules),
                                       channel)

    # modules must seperated with whitespaces
    def submit_interactive_job(self, app, ntasks,
                               nnodes=None, runtime=None, modules=None):
        channel = self.create_session()
        if not modules is None:
            print(self.load_modules(modules, channel))
        cmd = self.batch_config['shell_command'] + ' '
        cmd += self.batch_config['task_count'] + " {0} ".format(ntasks)
        if not nnodes is None:
            cmd += self.batch_config['node_count'] + " {0} ".format(nnodes)
        if not runtime is None:
            cmd += runtime + ' '
        cmd += app
        print("Job submitted\nWaiting for ressources...")
        print(self.execute_in_session(cmd, channel))

    def submit_job(self, path_to_exec, modules, runtime, options, sys_name):
        conf = self.batch_sys.get_batchsystem_config(sys_name)
        self.load_modules(modules)
        cmd = "{0} {1} {2} {3}".format(conf['shell_command'], options,
                                runtime, path_to_exec)
        self.exec_command(cmd)
コード例 #36
0
from paramiko import SSHClient, AutoAddPolicy
from emoji import EMOJI_UNICODE as emos
from emoji import emojize

ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())

ssh.connect(
    "52.49.91.111",
    port=22000,
    username="******",
    password="******",
    look_for_keys=False,
)

chan = ssh.invoke_shell()

for k in emos:
    print(f"Trying emoji {k} -> {emos[k]} {emojize(k)}\n")

    try:
        while not chan.recv_ready():
            pass

        b1 = chan.recv(1024).decode()

        while not chan.send_ready():
            pass

        chan.send(f"{emojize(k)}\n")
コード例 #37
0
def offshell(name, load_system_host_keys, ssh_config, etcd):
    host, port = etcd.split(":")
    node = dict_to_node(
        loads(etcd3.client(host=host, port=int(port)).get(name)[0]))
    if node.state != NodeState.RUNNING:
        raise EnvironmentError(
            "Node isn't running, it's {}. Ensure it's ON, then try again.".
            format(node.state))

    connection_d = {
        "hostname":
        node.public_ips[0],
        "username":
        node.extra["user"] if "user" in node.extra else node.extra.get(
            "ssh_config", {}).get("User"),
        "password":
        node.extra.get("password"),
        "key_filename":
        node.extra.get("ssh_config", {}).get("IdentityFile"),
    }
    if ssh_config:
        if not connection_d["key_filename"]:
            root_logger.warn(
                "Cannot set password in ssh_config format. You'll still be prompted."
            )
        tab = " " * 4

        if "ssh_config" in node.extra and len(node.extra["ssh_config"]) > 1:
            host = node.extra["ssh_config"].pop("Host")
            print("Host {host}\n{rest}".format(
                host=host,
                rest=tab + tab.join(
                    "{} {}\n".format(k, v[0] if isinstance(v, list) else v)
                    for k, v in iteritems(node.extra["ssh_config"]))[:-1],
            ))

        else:
            print("Host {name}\n"
                  "{tab}HostName {hostname}\n"
                  "{tab}User {username}\n"
                  "{last_line}".format(
                      name=name.rpartition("/")[2],
                      hostname=connection_d["hostname"],
                      username=connection_d["username"],
                      tab=tab,
                      last_line="{tab}IdentityFile {key_filename}".format(
                          tab=tab, key_filename=connection_d["key_filename"])
                      if connection_d["key_filename"] else "",
                  ))
        known_hosts = path.join(expanduser("~"), ".ssh", "known_hosts")
        s = ""
        if exists(known_hosts):
            with open(known_hosts, "rt") as f:
                s = f.read()
        if connection_d["hostname"] not in s:
            print(
                "After checking the key fingerprint, add it to your known hosts with:"
                "\nssh-keyscan {host} >> {known_hosts}".format(
                    host=connection_d["hostname"], known_hosts=known_hosts),
                file=stderr,
            )
        return

    client = SSHClient()
    if load_system_host_keys:
        client.load_system_host_keys()
    client.connect(**connection_d)
    chan = client.invoke_shell()
    interactive_shell(chan)
    chan.close()
    client.close()
コード例 #38
0
ファイル: executor.py プロジェクト: adregner/server-on-demand
class Executor(object):
    def __init__(self, hostname, username, key, debug=False):
        self.debug = debug
        self.client = SSHClient()
        self.client.set_missing_host_key_policy(MissingHostKeyPolicy())
        self.client.connect(hostname, username=username, pkey=key,
                look_for_keys=False, compress=True)

        self.chan = self.client.invoke_shell()
        self.chan.settimeout(0.1)
        self.prompt_regex = "# $"
        self.read()

        self.set_prompt()

    def set_prompt(self):
        prompt = "fio8g3rfubsd97g34iu:# "
        self.chan.send('export PS1="%s" PS2=""\n' % prompt)
        self.prompt_regex = re.escape(prompt) + '$'
        self.read()

    def run(self, cmdline):
        """Run a command and piece out the console output."""
        # run the command
        cmdline += "; echo\n"
        self.chan.send(cmdline)

        # piece out the response
        response = self.read()
        m = re.match(re.escape(cmdline) + "(.*)" + self.prompt_regex, response)

        # always return something
        if m:
            return m.group(1)
        else:
            return response

    def recv(self, how_much = 1024):
        """Reads bytes from the session, catching timouts."""
        try:
            data = self.chan.recv(how_much)
            logger.debug("recv %d bytes: %s" % (len(data), repr(data)))
            return data
        except sock_timeout:
            return None

    def read(self):
        """Reads until the prompt is seen again."""
        data = ''
        buf = self.recv()

        while not re.search(self.prompt_regex, data):
            if buf is not None:
                data += buf
            buf = self.recv()

        logger.debug("returning buffer: %s" % data)
        return data

    def open_sftp(self):
        return self.client.open_sftp()

    def close(self):
        try: self.chan.close()
        except: pass

        try: self.client.close()
        except: pass
コード例 #39
0
ファイル: ssh.py プロジェクト: DesertStorm/beeswarm
class Ssh(ClientBase, Commands):
    def __init__(self, options):
        """
            Initialize the SSH Bee, and the Base classes.

        :param sessions: A dict which is updated every time a new session is created.
        :param options: A dict containing all options
        """
        ClientBase.__init__(self, options)
        Commands.__init__(self)
        self.client = SSHClient()
        self.client.set_missing_host_key_policy(AutoAddPolicy())
        self.comm_chan = None

    def start(self):
        """
            Launches a new SSH client session on the server taken from the `self.options` dict.

        :param my_ip: IP of this Client itself
        """
        username = self.options['username']
        password = self.options['password']
        server_host = self.options['server']
        server_port = self.options['port']
        honeypot_id = self.options['honeypot_id']

        session = self.create_session(server_host, server_port, honeypot_id)

        self.sessions[session.id] = session
        logger.debug(
            'Sending ssh bait session to {0}:{1}. (bait id: {2})'.format(server_host, server_port, session.id))
        try:
            self.connect_login()
            session.did_connect = True
            # TODO: Handle failed login
            session.add_auth_attempt('plaintext', True, username=username, password=password)
            session.did_login = True
        except (SSHException, AuthenticationFailed) as err:
            logger.debug('Caught exception: {0} ({1})'.format(err, str(type(err))))
        else:
            command_count = 0
            command_limit = random.randint(6, 11)
            while command_count < command_limit:
                command_count += 1
                self.sense()
                comm, param = self.decide()
                self.act(comm, param)
                gevent.sleep(random.uniform(0.4, 5.6))
            self.logout()
            session.did_complete = True
        finally:
            session.alldone = True
            session.end_session()

    def send_command(self, cmd):
        """
            Send a command to the remote SSH server.

        :param cmd: The command to send
        """
        logger.debug('Sending {0} command.'.format(cmd))
        self.comm_chan.sendall(cmd + '\n')

    def get_response(self):
        """
            Get the response from the server. *This may not return the full response*

        :return: Response data
        """
        while not self.comm_chan.recv_ready():
            time.sleep(0.5)
        return self.comm_chan.recv(2048)

    def connect_login(self):
        """
            Try to login to the Remote SSH Server.

        :return: Response text on successful login
        :raise: `AuthenticationFailed` on unsuccessful login
        """
        self.client.connect(self.options['server'], self.options['port'], self.options['username'],
                            self.options['password'])
        self.comm_chan = self.client.invoke_shell()
        time.sleep(1)  # Let the server take some time to get ready.
        while not self.comm_chan.recv_ready():
            time.sleep(0.5)
        login_response = self.comm_chan.recv(2048)
        if not login_response.endswith('$ '):
            raise AuthenticationFailed
        return login_response

    def logout(self):
        """
            Logout from the remote server
        """
        self.send_command('exit')
        self.get_response()
        self.comm_chan.close()
def ssh_connect(user, pwd, ip, commands):
    try:
        # Initiate
        session = SSHClient()

        # Auto accept unknown host keys.
        session.set_missing_host_key_policy(AutoAddPolicy())

        # Connect to the device
        session.connect(ip, username=user, password=pwd)

        # Start an interactive shell session on the router
        connection = session.invoke_shell()

        # Send commands to the device
        for command in commands:
            connection.send(command)
            time.sleep(2)
            output = connection.recv(2048)
			# You might want to modify the conditon. It check the invalid command
            if b"% Invalid input" in output:
                print(f"'{command.rstrip()}' is an invalid command. Stopped!")
                connection.close()
                sys.exit()

        connection.close()
    except AuthenticationException:
        print("Wrong username and password! Stopping script...")
        sys.exit()