Exemple #1
0
 def manual_auth(self):
     """
     手动授权,默认使用密码认证方式
     :return:
     """
     default_auth = 'p'
     auth = default_auth
     # auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
     if len(auth) == 0:
         auth = default_auth
     if auth == 'r':
         default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
         path = input('RSA key [%s]: ' % default_path)
         if len(path) == 0:
             path = default_path
         try:
             key = paramiko.RSAKey.from_private_key_file(path)
         except paramiko.PasswordRequiredException:
             key = paramiko.RSAKey.from_private_key_file(path, self.password)
         self.transport.auth_publickey(self.username, key)
     elif auth == 'd':
         default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
         path = input('DSS key [%s]: ' % default_path)
         if len(path) == "0":
             path = default_path
         try:
             key = paramiko.DSSKey.from_private_key_file(path)
         except paramiko.PasswordRequiredException:
             key = paramiko.DSSKey.from_private_key_file(path, self.password)
         self.transport.auth_publickey(self.username, key)
     else:
         self.transport.auth_password(self.username, self.password)
Exemple #2
0
    def manual_auth(username, hostname):
        if key_type == 'ssh-password':  #认证类型
            default_auth = 'p'
        elif key_type == 'ssh-key':
            default_auth = 'd'
        auth = default_auth
        if len(auth) == 0:
            auth = default_auth

        if auth == 'r':
            default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
            path = input('RSA key [%s]: ' % default_path)
            if len(path) == 0:
                path = default_path
            try:
                key = paramiko.RSAKey.from_private_key_file(path)
            except paramiko.PasswordRequiredException:
                password = getpass.getpass('RSA key password: '******'d':
            default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
            path = input('DSS key [%s]: ' % default_path)
            if len(path) == 0:
                path = default_path
            try:
                key = paramiko.DSSKey.from_private_key_file(path)
            except paramiko.PasswordRequiredException:
                password = getpass.getpass('DSS key password: ')
                key = paramiko.DSSKey.from_private_key_file(path, password)
            t.auth_publickey(username, key)
        else:
            pw = passwd  #密码
            t.auth_password(username, pw)
Exemple #3
0
def manual_auth(username,hostname):
    default_auth='p'
    auth=input('Auth by (p)ssword,(r)sa key,or (d)ss key?[%s]' %default_auth)
    if len(auth)==0:
        auth=default_auth
        #判断key是否是rsa
    if auth=='r':
        default_path=os.path.join(os.environ['HOME'],'.ssh','id_rsa')
        path=input('RSA key [%s]:'%default_auth)
        if len(path)==0:
            path=default_auth
        try:
            key=paramiko.RSAKey._from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password=getpass.getpass('RSA key password:'******'d':
        default_path=os.path.join(os.environ['HOME'],'.ssh','id_dsa')
        path=input('DSS key [%s]:'%default_auth)
        if len(path)==0:
            path=default_auth
        try:
            key=paramiko.DSSKey.from_private_key_file(path)
        except: paramiko.PasswordRequiredException:
            password=getpass.getpass('DSS key password:')
            key
Exemple #4
0
def manual_auth(t, username, hostname, password):
    default_auth = "p"
    # auth = input(
    #     "Auth by (p)assword, (r)sa key, or (d)ss key? [%s] " % default_auth
    # )

    # if len(auth) == 0:
    #     auth = default_auth
    auth = default_auth
    if auth == "r":
        default_path = os.path.join(os.environ["HOME"], ".ssh", "id_rsa")
        path = input("RSA key [%s]: " % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass("RSA key password: "******"d":
        default_path = os.path.join(os.environ["HOME"], ".ssh", "id_dsa")
        path = input("DSS key [%s]: " % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass("DSS key password: "******"Password for %s@%s: " % (username, hostname))
        # t.auth_password(username, pw)
        t.auth_password(username, password)
def auth_credentials():
    # get hostname
    username = ""
    if len(sys.argv) > 1:
        hostname = sys.argv[1]
        if hostname.find("@") >= 0:
            username, hostname = hostname.split("@")
    else:
        hostname = input("Hostname: ")
    if len(hostname) == 0:
        print("*** Hostname required.")
        sys.exit(1)

    if hostname.find(":") >= 0:
        hostname, portstr = hostname.split(":")
        Port = int(portstr)

    # get username
    if username == "":
        default_username = getpass.getuser()
        username = input("Username [%s]: " % default_username)
        if len(username) == 0:
            username = default_username
    if not UseGSSAPI:
        password = getpass.getpass("Password for %s@%s: " %
                                   (username, hostname))
    else:
        password = None

    return username, password
Exemple #6
0
 def manual_auth(self):
     """
     手动授权,默认使用密码认证方式
     :return:
     """
     default_auth = 'p'
     auth = default_auth
     # auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
     if len(auth) == 0:
         auth = default_auth
     if auth == 'r':
         default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
         path = input('RSA key [%s]: ' % default_path)
         if len(path) == 0:
             path = default_path
         try:
             key = paramiko.RSAKey.from_private_key_file(path)
         except paramiko.PasswordRequiredException:
             key = paramiko.RSAKey.from_private_key_file(path, self.password)
         self.transport.auth_publickey(self.username, key)
     elif auth == 'd':
         default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
         path = input('DSS key [%s]: ' % default_path)
         if len(path) == "0":
             path = default_path
         try:
             key = paramiko.DSSKey.from_private_key_file(path)
         except paramiko.PasswordRequiredException:
             key = paramiko.DSSKey.from_private_key_file(path, self.password)
         self.transport.auth_publickey(self.username, key)
     else:
         self.transport.auth_password(self.username, self.password)
Exemple #7
0
def manual_auth(username, hostname):
    default_auth = 'p'
    auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
    if len(auth) == 0:
        auth = default_auth

    if auth == 'r':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        path = input('RSA key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('RSA key password: '******'d':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
        path = input('DSS key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('DSS key password: '******'Password for %s@%s: ' % (username, hostname))
        t.auth_password(username, pw)
Exemple #8
0
def manual_auth(t, hostname, username, password):
    default_auth = 'p'
    # auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
    # if len(auth) == 0:
    #     auth = default_auth
    auth = default_auth
    if auth == 'r':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        path = input('RSA key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('RSA key password: '******'d':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
        path = input('DSS key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('DSS key password: '******'Password for %s@%s: ' % (username, hostname))
        t.auth_password(username, password)
Exemple #9
0
def manual_auth(username, hostname):
    default_auth = "p"
    auth = input(
        "Auth by (p)assword, (r)sa key, or (d)ss key? [%s] " % default_auth
    )
    if len(auth) == 0:
        auth = default_auth

    if auth == "r":
        default_path = os.path.join(os.environ["HOME"], ".ssh", "id_rsa")
        path = input("RSA key [%s]: " % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass("RSA key password: "******"d":
        default_path = os.path.join(os.environ["HOME"], ".ssh", "id_dsa")
        path = input("DSS key [%s]: " % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass("DSS key password: "******"Password for %s@%s: " % (username, hostname))
        t.auth_password(username, pw)
Exemple #10
0
def manual_auth(username, hostname, t, password):
    default_auth = "p"
    auth = default_auth
    if len(auth) == 0:
        auth = default_auth

    if auth == "r":
        default_path = os.path.join(os.environ["HOME"], ".ssh", "id_rsa")
        path = input("RSA key [%s]: " % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass("RSA key password: "******"d":
        default_path = os.path.join(os.environ["HOME"], ".ssh", "id_dsa")
        path = input("DSS key [%s]: " % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass("DSS key password: ")
            key = paramiko.DSSKey.from_private_key_file(path, password)
        t.auth_publickey(username, key)
    else:
        t.auth_password(username, password)
Exemple #11
0
def run_setup(ssh_host, ssh_port, ssh_user, ssh_pass):
    def writeall(chan):
        while True:
            data = chan.recv(256)
            if not data:
                sys.stdout.write("\r\n*** EOF ***\r\n\r\n")
                sys.stdout.flush()
                break
            msg = str(data, encoding='utf-8')
            sys.stdout.write(msg)
            sys.stdout.flush()

    # now, connect and use paramiko Transport to negotiate SSH2 across the connection
    try:
        t = paramiko.Transport((ssh_host, ssh_port))
        t.connect(hostkey=None,
                  username=ssh_user,
                  password=ssh_pass,
                  gss_host=socket.getfqdn(ssh_host))
        sftp = paramiko.SFTPClient.from_transport(t)

        sftp.put(SETUP_SSH_PY_PATH, SETUP_SSH_PY_PATH)
        sftp.put(SSHD_CONFIG_TPL_PATH, SSHD_CONFIG_TPL_PATH)
        sftp.put(AUTHORIZED_KEYS_PATH, AUTHORIZED_KEYS_PATH)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(policy=paramiko.AutoAddPolicy)
        ssh.connect(hostname=ssh_host,
                    port=ssh_port,
                    username=ssh_user,
                    password=ssh_pass)
        channel = ssh.invoke_shell()
        target_user = input('New admin name [admin]:') or "admin"
        target_port = input('New ssh port [2200-2299]:') or randrange(
            2200, 2299)
        writer = threading.Thread(target=writeall, args=(channel, ))
        writer.start()
        channel.send(
            f"python setup_ssh.py -u {target_user} -p {target_port}\n")
        try:
            while True:
                d = sys.stdin.read(1)
                if not d:
                    break
                channel.send(d)
        except EOFError:
            # user hit ^Z or F6
            pass
        ssh.close()
        t.close()

    except Exception as e:
        print("*** Caught exception: %s: %s" % (e.__class__, e))
        traceback.print_exc()
        try:
            t.close()
        except:
            pass
        sys.exit(1)
Exemple #12
0
    def _manual_auth(self, t, username, hostname, mode, password, keypass):
        default_auth = "p"
        path = None
        if mode is None:
            mode = input(
                "%s: Auth by (p)assword, (r)sa key, or (d)ss key? [%s] " %
                (hostname, default_auth))
        if len(mode) == 0:
            mode = default_auth

        if mode == "r":
            password, path = self._rsa(t,
                                       username=username,
                                       path=keypass,
                                       password=password)
        elif mode == "d":
            password, path = self._dss(t,
                                       username=username,
                                       path=keypass,
                                       password=password)
        else:
            if password is None:
                password = getpass.getpass("Password for %s@%s: " %
                                           (username, hostname))
            t.auth_password(username, password)
        return mode, password, path
Exemple #13
0
    def create_droplet(self, droplet_size: str) -> str:
        game_server_droplets = self.__get_game_server_droplets()
        if len(game_server_droplets) > 0:
            query = input(
                'There exist already {} {} server. Continue with creation? [Y/n]'
                .format(len(game_server_droplets), self.game.name()))
            fl = query[0].lower()
            if query != 'Y':
                print('Aborting creation.')
                sys.exit(0)

        print('Creating {} server...'.format(self.game.name()))

        manager = digitalocean.Manager(token=self.token)
        keys = manager.get_all_sshkeys()

        droplet = digitalocean.Droplet(
            token=self.token,
            name=self.serverName,
            region='fra1',
            image='docker-20-04',
            size_slug=droplet_size,
            ssh_keys=keys,  # Add all keys
            backups=False)

        loading = ['\\', '-', '/', '|']
        loading_inc = 0
        droplet.create()

        droplet_created = False
        while not droplet_created:
            for action in droplet.get_actions():
                action.load()
                loading_inc += 1
                print('loading... ', str(loading[loading_inc % 4]), end='\r')
                if action.status == "completed":
                    droplet_created = True
                    break
                if action.status == "errored":
                    print("Error when creating droplet.")
                    sys.exit(1)

        # Request all droplets and find recently created droplet
        # We do this as the created droplet object is missing some information, e.g. ip address
        found_droplet = False
        droplets = manager.get_all_droplets()
        for d in droplets:
            if d.id == droplet.id:
                droplet = d
                found_droplet = True

        if (not found_droplet):
            print("Error: Could not setup droplet.")
            sys.exit(1)

        self.hostname = droplet.ip_address
Exemple #14
0
def manual_auth(username, hostname):
    default_auth = 'p'
    auth = input('Auth by (p)assword or (k)ey file? [%s] ' % default_auth)
    if len(auth) == 0:
        auth = default_auth

    if auth == 'k':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        path = input('Private key file [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.load_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('Private key password: '******'Password for %s@%s: ' % (username, hostname))
        t.auth_password(username, pw)
Exemple #15
0
def manual_auth(t, hostname, username, password):
    """
    验证登录
    :param t:
    :param hostname: 主机地址
    :param username: 主机账户
    :param password: 主机密码
    :return:
    """
    default_auth = 'p'  # p:表示以用户名、密码登录,r:以公钥登录(免登陆),d:未知,这里我们用 p 登录
    #auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
    # if len(auth) == 0:
    #     auth = default_auth
    auth = default_auth
    if auth == 'r':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        path = input('RSA key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('RSA key password: '******'d':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
        path = input('DSS key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('DSS key password: '******'Password for %s@%s: ' % (username, hostname))
        t.auth_password(username, password)  # 验证登录
Exemple #16
0
 def _rsa(self, t, username, path=None, password=None):
     default_path = os.path.join(os.environ["HOME"], ".ssh", "id_rsa")
     if path is None:
         path = input("RSA key [%s]: " % default_path)
     if len(path) == 0:
         path = default_path
     try:
         key = paramiko.RSAKey.from_private_key_file(path)
     except paramiko.PasswordRequiredException:
         if password is None:
             password = getpass.getpass("RSA key password: ")
         key = paramiko.RSAKey.from_private_key_file(path, password)
     t.auth_publickey(username, key)
     return password, path
Exemple #17
0
def main():
    nav = Nav()
    # 这里需要加一个登陆判断
    nav.print_nav()

    try:
        while True:
            try:
                option = input("\033[1;32mOpt or ID>:\033[0m ").strip()
            except EOFError:
                nav.print_nav()
                continue
            except KeyboardInterrupt:
                sys.exit(0)
            if option in ['P', 'p', '\n', '']:
                nav.search()
                # nav.print_search_result()
                continue
            # if option.startswith('/'):
            #     nav.search(option.lstrip('/'))
            #     nav.print_all_hosts()
            # elif gid_pattern.match(option):
            #     nav.get_asset_group_member(str_r=option)
            #     nav.print_search_result()
            # elif option in ['G', 'g']:
            #     nav.print_asset_group()
            #     continue
            # elif option in ['E', 'e']:
            #     nav.exec_cmd()
            #     continue
            # elif option in ['U', 'u']:
            #     nav.upload()
            # elif option in ['D', 'd']:
            #     nav.download()
            elif option in ['H', 'h']:
                nav.print_nav()
            elif option in ['Q', 'q', 'exit']:
                sys.exit()
            else:
                nav.search(option)

                # if len(nav.search_result) == 1:
                #     print('Only match Host:  %s ' % nav.search_result[0].hostname)
                #     nav.try_connect()
                # else:
                #     nav.print_search_result()

    except IndexError as e:
        color_print(e)
Exemple #18
0
def manual_auth(bind_host, t):
    if bind_host.remote_user.auth_type == 'ssh-key':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        path = input('RSA key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('RSA key password: ')
            key = paramiko.RSAKey.from_private_key_file(path, password)
        t.auth_publickey(bind_host.remote_user.username, key)
    else:
        pw = bind_host.remote_user.password
        t.auth_password(bind_host.remote_user.username, pw)
Exemple #19
0
def manual_auth(t, username, hostname, key_file):
    default_auth = 'password_auth'

    if len(key_file) == 0:
        key_file = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        auth = 'rsa_auth'
    else:
        with open('key_file.txt', 'r') as f:
            first_line = f.readline()
            if "RSA" in first_line:
                auth = 'rsa_auth'
            else:
                auth = 'dsa_auth'

    if not os.path.isfile(key_file):
        key_file = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
        auth = 'dsa_auth'
    else:
        multipy_logger.warn("Unable to locate key file. Defaulting to " + auth)
        auth = default_auth

    if auth == 'rsa_auth':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        if len(key_file) == 0:
            key_file = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(key_file)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('RSA key password: '******'dsa_auth':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
        path = input('DSS key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('DSS key password: '******'Password for %s@%s: ' % (username, hostname))
        t.auth_password(username, pw)
    def manual_auth(self, username, hostname, pwd, key_file):
        # 默认密码登陆
        auth = 'p'

        if key_file:
            # 有key 先用key
            auth = 'r'

        if auth == 'r':
            # default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
            # path = input('RSA key [%s]: ' % default_path)
            # if len(path) == 0:
            #     path = default_path
            try:
                # 尝试使用key登陆
                key = paramiko.RSAKey.from_private_key_file(key_file)
                # except paramiko.PasswordRequiredException:
                #     password = getpass.getpass('RSA key password: '******'key 登陆')
            except:
                # key登陆失败 使用密码
                print('key 不好使,还是得用密码')
                self.manual_auth(username, hostname, pwd, None)
        elif auth == 'd':
            default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
            path = input('DSS key [%s]: ' % default_path)
            if len(path) == 0:
                path = default_path
            try:
                key = paramiko.DSSKey.from_private_key_file(path)
            except paramiko.PasswordRequiredException:
                password = getpass.getpass('DSS key password: '******'Password for %s@%s: ' % (username, hostname))
            # pw = '123456'
            pw = pwd
            self.t.auth_password(username, pw)
Exemple #21
0
def host_action(username, command, key_file, hostname, script_file_name, files_to_transfer, keys, match):
    if command:
        multipy_logger.info("Executing " + command + " on " + hostname)
    else:
        multipy_logger.info("Executing " + script_file_name + " on " + hostname)

    if len(hostname) == 0:
        multipy_logger.error('*** Hostname required.')
        sys.exit(1)
    port = 22
    if hostname.find(':') >= 0:
        hostname, portstr = hostname.split(':')
        port = int(portstr)

    # now connect
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((hostname, port))
    except Exception as e:
        multipy_logger.error('*** Connect failed: ' + str(e))
        traceback.print_exc()
        sys.exit(1)

    try:
        t = paramiko.Transport(sock)
        try:
            t.start_client()
        except paramiko.SSHException:
            multipy_logger.error('*** SSH negotiation failed.')
            sys.exit(1)
        # check server's host key -- this is important.
        key = t.get_remote_server_key()
        if hostname not in keys:
            multipy_logger.warn('*** WARNING: Unknown host key!')
        elif key.get_name() not in keys[hostname]:
            multipy_logger.warn('*** WARNING: Unknown host key!')
        elif keys[hostname][key.get_name()] != key:
            multipy_logger.error('*** WARNING: Host key has changed!!!')
            sys.exit(1)
        else:
            multipy_logger.info('*** Host key OK.')

        # get username
        if username == '':
            default_username = getpass.getuser()
            username = input('Username [%s]: ' % default_username)
            if len(username) == 0:
                username = default_username

        agent_auth(t, username)
        if not t.is_authenticated():
            manual_auth(t, username, hostname, key_file)
        if not t.is_authenticated():
            print('*** Authentication failed. :(')
            t.close()
            sys.exit(1)

        multipy_logger.info(hostname + ': Opening session')
        chan = t.open_session()
        buf_size = -1
        timeout = None
        chan.settimeout(timeout)
        command_lines = []

        stdin = chan.makefile('wb', buf_size)
        stdout = chan.makefile('r', buf_size)
        stderr = chan.makefile_stderr('r', buf_size)

        if command:
            command_lines.append(command+"\n")
        else:
            with open(script_file_name) as script_file:
                command_lines = script_file.readlines()

        chan.invoke_shell()
        multipy_logger.info("Match "+match)
        for command_line in command_lines:

            multipy_logger.info(hostname + ':' + command_line)
            chan.send(command_line)

            buff = chan.recv(1024)
            while chan.recv_ready():
                resp = chan.recv(1024)
                buff += resp

            if not match or (match in buff):
                print hostname + ':\n' + buff


        chan.close()
        t.close()

    except Exception as e:
        multipy_logger.error('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
        traceback.print_exc()
        try:
            t.close()
        except:
            pass
        sys.exit(1)
Exemple #22
0
def connectToHost(host):
    # Paramiko client configuration
    UseGSSAPI = True             # enable GSS-API / SSPI authentication
    DoGSSAPIKeyExchange = True
    port = 22

    # get hostname
    username = ''
    if len(host) > 1:
        hostname = host
        if hostname.find('@') >= 0:
            username, hostname = hostname.split('@')
    else:
        hostname = input('Hostname: ')
    if len(hostname) == 0:
        print('*** Hostname required.')
        sys.exit(1)

    if hostname.find(':') >= 0:
        hostname, portstr = hostname.split(':')
        port = int(portstr)

    # get username
    if username == '':
        default_username = getpass.getuser()
        username = input('Username [%s]: ' % default_username)
        if len(username) == 0:
            username = default_username
    if not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange):
        password = getpass.getpass('Password for %s@%s: ' % (username, hostname))

    # now, connect and use paramiko Client to negotiate SSH2 across the connection
    try:
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.WarningPolicy())
        print('*** Connecting...')
        if not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange):
            client.connect(hostname, port, username, password)
        else:
            # SSPI works only with the FQDN of the target host
            hostname = socket.getfqdn(hostname)
            try:
                client.connect(hostname, port, username, gss_auth=UseGSSAPI,
                               gss_kex=DoGSSAPIKeyExchange)
            except Exception:
                password = getpass.getpass('Password for %s@%s: ' % (username, hostname))
                client.connect(hostname, port, username, password)

        chan = client.invoke_shell()
        print(repr(client.get_transport()))
        print('*** Here we go!\n')
        interactive.interactive_shell(chan)
        chan.close()
        client.close()

    except Exception as e:
        print('*** Caught exception: %s: %s' % (e.__class__, e))
        traceback.print_exc()
        try:
            client.close()
        except:
            pass
        sys.exit(1)
Exemple #23
0
def ssh_login():
    port = 22
    auth_type = u''
    hostname = input("hostname==>")
    username = input("username==>")
    password = input("password==>")
    # now connect
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((hostname, port))

        t = paramiko.Transport(sock)
        try:
            t.start_client()
        except paramiko.SSHException:
            print('*** SSH negotiation failed.')
            sys.exit(1)

        try:
            keys = paramiko.util.load_host_keys(
                os.path.expanduser('~/.ssh/known_hosts'))
        except IOError:
            try:
                keys = paramiko.util.load_host_keys(
                    os.path.expanduser('~/ssh/known_hosts'))
            except IOError:
                print('*** Unable to open host keys file')
                keys = {}

        # check server's host key -- this is important.
        key = t.get_remote_server_key()
        if hostname not in keys:
            print('*** WARNING: Unknown host key!')
        elif key.get_name() not in keys[hostname]:
            print('*** WARNING: Unknown host key!')
        elif keys[hostname][key.get_name()] != key:
            print('*** WARNING: Host key has changed!!!')
            sys.exit(1)
        else:
            print('*** Host key OK.')
        if auth_type == u'SSH/KEY':
            auth_key(t, username)
        else:
            # password = host_and_sysuser_obj.sysuser.password
            auth_pw(t, username, password)
        if not t.is_authenticated():
            print('*** Authentication failed. :(')
            t.close()
            sys.exit(1)

        chan = t.open_session()
        chan.get_pty()
        chan.invoke_shell()
        print('*** Here we go!\n')
        interactive.interactive_shell(chan)
        chan.close()
        t.close()

    except Exception as e:
        print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
        traceback.print_exc()
        try:
            t.close()
        except Exception:
            pass
        sys.exit(1)
Exemple #24
0
def demo_func(username,hostname):
    def agent_auth(transport, username):
        """
        Attempt to authenticate to the given transport using any of the private
        keys available from an SSH agent.
        """
        
        agent = paramiko.Agent()
        agent_keys = agent.get_keys()
        if len(agent_keys) == 0:
            return
            
        for key in agent_keys:
            print('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()))
            try:
                transport.auth_publickey(username, key)
                print('... success!')
                return
            except paramiko.SSHException:
                print('... nope.')
    
    
    def manual_auth(username, hostname):
        '''
        default_auth = 'p'
        auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
        if len(auth) == 0:
            auth = default_auth
    
        if auth == 'r':
            default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
            path = input('RSA key [%s]: ' % default_path)
            if len(path) == 0:
                path = default_path
            try:
                key = paramiko.RSAKey.from_private_key_file(path)
            except paramiko.PasswordRequiredException:
                password = getpass.getpass('RSA key password: '******'d':
            default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
            path = input('DSS key [%s]: ' % default_path)
            if len(path) == 0:
                path = default_path
            try:
                key = paramiko.DSSKey.from_private_key_file(path)
            except paramiko.PasswordRequiredException:
                password = getpass.getpass('DSS key password: '******'''
        #pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
       
        pw=host().get_user_pwd(hostname, username)
        #print pw
        t.auth_password(username, pw)
    
    
    # setup logging
    #paramiko.util.log_to_file('demo.log')
    '''
    username = ''
    if len(sys.argv) > 1:
        hostname = sys.argv[1]
        if hostname.find('@') >= 0:
            username, hostname = hostname.split('@')
    else:
        hostname = input('Hostname: ')
    if len(hostname) == 0:
        print('*** Hostname required.')
        sys.exit(1)
        '''
    port = 22
    '''
    if hostname.find(':') >= 0:
        hostname, portstr = hostname.split(':')
        port = int(portstr)
    '''
    # now connect
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((hostname, port))
    except Exception as e:
        print('*** Connect failed: ' + str(e))
        traceback.print_exc()
        sys.exit(1)
    
    try:
        t = paramiko.Transport(sock)
        try:
            t.start_client()
        except paramiko.SSHException:
            print('*** SSH negotiation failed.')
            sys.exit(1)
    
        try:
            keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
        except IOError:
            try:
                keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
            except IOError:
                print('*** Unable to open host keys file')
                keys = {}
    
        # check server's host key -- this is important.
        key = t.get_remote_server_key()
        if hostname not in keys:
            print('*** WARNING: Unknown host key!')
        elif key.get_name() not in keys[hostname]:
            print('*** WARNING: Unknown host key!')
        elif keys[hostname][key.get_name()] != key:
            print('*** WARNING: Host key has changed!!!')
            sys.exit(1)
        else:
            print('*** Host key OK.')
    
        # get username
        if username == '':
            default_username = getpass.getuser()
            username = input('Username [%s]: ' % default_username)
            if len(username) == 0:
                username = default_username
    
        agent_auth(t, username)
        if not t.is_authenticated():
            manual_auth(username, hostname)
        if not t.is_authenticated():
            print('*** Authentication failed. :(')
            t.close()
            sys.exit(1)
    
        chan = t.open_session()
        chan.get_pty()
        chan.invoke_shell()
        print('*** Here we go!\n')
        interactive.interactive_shell(chan,hostname,username)
        chan.close()
        t.close()
    
    except Exception as e:
        print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
        traceback.print_exc()
        try:
            t.close()
        except:
            pass
        sys.exit(1)
Exemple #25
0
default_password = ""
default_hostname = ""
default_passphrase = ""
Port = 2222
UsePasswd = False

# get hostname
username = default_username
if len(sys.argv) > 1:
    hostname = sys.argv[1]
    if hostname.find("@") >= 0:
        username, hostname = hostname.split("@")
else:
    hostname = default_hostname
    if len(hostname) == 0:
        hostname = input("Hostname: ")

if len(hostname) == 0:
    print("*** Hostname required.")
    sys.exit(1)

if hostname.find(":") >= 0:
    hostname, portstr = hostname.split(":")
    Port = int(portstr)

# get username
username = default_username
if default_username == "":
    default_username = getpass.getuser()
    username = input("Username [%s]: " % default_username)
    if len(username) == 0:
def shell_loop():
    print("Entered Shell")
    SHELL_STATUS_RUN = 1  # for running the loop
    directorySetup()

    while SHELL_STATUS_RUN:
        prompt = raw_input('%s@%s: ' % (username, hostname))
        #fileNameFind = prompt.split()
        #print fileNameFind
        translatedPrompt = translate(prompt)
        print translatedPrompt
        #global client
        if (translatedPrompt == "close"):
            try:
                SHELL_STATUS_RUN = 0
                target.write(
                    strftime("[%d-%m-%Y] [%H:%M:%S]", gmtime()) +
                    ' ' +  # Input
                    username + '@' + hostname + ':' + str(port) + ' >> ' +
                    translatedPrompt + '\n')  #
                output = client_stdout.read()
                target.write(
                    strftime("[%d-%m-%Y] [%H:%M:%S]", gmtime()) +
                    ' ' +  # Output
                    username + '@' + hostname + ':' + str(port) + ' << ' +
                    "Exiting Program." + '\n')  #
            except:
                print("Exiting...")
        elif (translatedPrompt == "sftp"):  # should be elif
            try:
                print("1")
                #trans = paramiko.Transport((hostname, port))
                print("2")
                sftp = client.open_sftp()
                print("3")
                sftp.chdir("/private/var/mobile/Media/DCIM/117APPLE")
                print("4")
                fileName = input("Filename for SFTP transfer: ")
                fileTransferPath = (r"C:\Users\Josh\Desktop\Evidence\\" +
                                    fileName)
                sftp.get(fileName, fileTransferPath)
                target.write(
                    strftime("[%d-%m-%Y] [%H:%M:%S]", gmtime()) +
                    ' ' +  # Input
                    username + '@' + hostname + ':' + str(port) + ' << ' +
                    "Transferring " + fileName + " to " + innerDirPath + "." +
                    '\n')  #
                target.write(
                    strftime("[%d-%m-%Y] [%H:%M:%S]", gmtime()) +
                    ' ' +  # Output
                    username + '@' + hostname + ':' + str(port) + ' >> ' +
                    "Transferred " + fileName + " to " + innerDirPath + "." +
                    '\n')  #
                print("Successfully transferred " + fileName + " to " +
                      innerDirPath + ".")
                sftp.close()
            except IOError:
                print("The file could not be found.")
            except:
                print("An unexpected error occured in SFTP.")

        elif (translatedPrompt == "md5sum"
              ):  #translatedPrompt.split(""))[0] == "md5sum"
            veriFile = input("Please type the name of the file to verify: ")
            validated = verifyMD5(veriFile)
        elif (translatedPrompt == "sha256sum"
              ):  #translatedPrompt.split(""))[0] == "sha256sum"
            veriFile = input("Please type the name of the file to verify: ")
            validated = verifySHA256(veriFile)
        else:
            try:
                client_stdin, client_stdout, client_stderr = client.exec_command(
                    translatedPrompt)
                output = client_stdout.read()
                target.write(
                    strftime("[%d-%m-%Y] [%H:%M:%S]", gmtime()) + ' ' +
                    username + '@' + hostname + ':' + str(port) + ' << ' +
                    output)
                print "Output: ", output
            except:
                print(
                    "An unexpected error occured in non-dictionary command execution."
                )

    target.close()
    trans.close()
    client.close()
Exemple #27
0
import paramiko
import getopt
import threading
import sys
import socket
import subprocess
import getpass
import traceback
from paramiko.py3compat import input
host_key = paramiko.RSAKey(filename='test_rsa.key')
username = ''
passwd = ''

if username == '':
    default_username = getpass.getuser()
    username = input('username [%s]: ' % default_username)
if len(username) == 0:
    username = default_username
if passwd == '':
    passwd = input('Password:'******'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
Exemple #28
0
def ssh_login():
    port = 22
    auth_type = u''
    hostname = input("hostname==>")
    username = input("username==>")
    password = input("password==>")
    # now connect
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((hostname, port))

        t = paramiko.Transport(sock)
        try:
            t.start_client()
        except paramiko.SSHException:
            print('*** SSH negotiation failed.')
            sys.exit(1)

        try:
            keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
        except IOError:
            try:
                keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
            except IOError:
                print('*** Unable to open host keys file')
                keys = {}

        # check server's host key -- this is important.
        key = t.get_remote_server_key()
        if hostname not in keys:
            print('*** WARNING: Unknown host key!')
        elif key.get_name() not in keys[hostname]:
            print('*** WARNING: Unknown host key!')
        elif keys[hostname][key.get_name()] != key:
            print('*** WARNING: Host key has changed!!!')
            sys.exit(1)
        else:
            print('*** Host key OK.')
        if auth_type == u'SSH/KEY':
            auth_key(t, username)
        else:
            # password = host_and_sysuser_obj.sysuser.password
            auth_pw(t, username, password)
        if not t.is_authenticated():
            print('*** Authentication failed. :(')
            t.close()
            sys.exit(1)

        chan = t.open_session()
        chan.get_pty()
        chan.invoke_shell()
        print('*** Here we go!\n')
        interactive.interactive_shell(chan)
        chan.close()
        t.close()

    except Exception as e:
        print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
        traceback.print_exc()
        try:
            t.close()
        except Exception:
            pass
        sys.exit(1)
Exemple #29
0
# setup logging
paramiko.util.log_to_file('demo_simple.log')
# Paramiko client configuration
UseGSSAPI = True  # enable GSS-API / SSPI authentication
DoGSSAPIKeyExchange = True
port = 22

# get hostname
username = ''
if len(sys.argv) > 1:
    hostname = sys.argv[1]
    if hostname.find('@') >= 0:
        username, hostname = hostname.split('@')
else:
    hostname = input('Hostname: ')
if len(hostname) == 0:
    print('*** Hostname required.')
    sys.exit(1)

if hostname.find(':') >= 0:
    hostname, portstr = hostname.split(':')
    port = int(portstr)

# get username
if username == '':
    default_username = getpass.getuser()
    username = input('Username [%s]: ' % default_username)
    if len(username) == 0:
        username = default_username
if not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange):
Exemple #30
0
)  # enable "gssapi-with-mic" authentication, if supported by your python installation
DoGSSAPIKeyExchange = (
    paramiko.GSS_AUTH_AVAILABLE
)  # enable "gssapi-kex" key exchange, if supported by your python installation
# UseGSSAPI = False
# DoGSSAPIKeyExchange = False
port = 22

# get hostname
username = ""
if len(sys.argv) > 1:
    hostname = sys.argv[1]
    if hostname.find("@") >= 0:
        username, hostname = hostname.split("@")
else:
    hostname = input("Hostname: ")
if len(hostname) == 0:
    print("*** Hostname required.")
    sys.exit(1)

if hostname.find(":") >= 0:
    hostname, portstr = hostname.split(":")
    port = int(portstr)


# get username
if username == "":
    default_username = getpass.getuser()
    username = input("Username [%s]: " % default_username)
    if len(username) == 0:
        username = default_username
Exemple #31
0
def main(user_profile_obj, bind_host_obj, login_info):
    # setup logging
    paramiko.util.log_to_file('demo.log')

    username = login_info['username']
    # if len(sys.argv) > 1:
    #     hostname = sys.argv[1]
    #     if hostname.find('@') >= 0:
    #         username, hostname = hostname.split('@')
    # else:
    hostname = login_info['hostname']
    if len(hostname) == 0:
        print('*** Hostname required.')
        sys.exit(1)
    port = 22
    if hostname.find(':') >= 0:
        hostname, portstr = hostname.split(':')
        port = int(portstr)

    # now connect
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((hostname, port))
    except Exception as e:
        print('*** Connect failed: ' + str(e))
        traceback.print_exc()
        sys.exit(1)

    try:
        t = paramiko.Transport(sock)
        try:
            t.start_client()
        except paramiko.SSHException:
            print('*** SSH negotiation failed.')
            sys.exit(1)

        try:
            keys = paramiko.util.load_host_keys(
                os.path.expanduser('~/.ssh/known_hosts'))
        except IOError:
            try:
                keys = paramiko.util.load_host_keys(
                    os.path.expanduser('~/ssh/known_hosts'))
            except IOError:
                print('*** Unable to open host keys file')
                keys = {}

        # check server's host key -- this is important.
        key = t.get_remote_server_key()
        if hostname not in keys:
            print('*** WARNING: Unknown host key!')
        elif key.get_name() not in keys[hostname]:
            print('*** WARNING: Unknown host key!')
        elif keys[hostname][key.get_name()] != key:
            print('*** WARNING: Host key has changed!!!')
            sys.exit(1)
        else:
            print('*** Host key OK.')

        # get username
        if username == '':
            default_username = getpass.getuser()
            username = input('Username [%s]: ' % default_username)
            if len(username) == 0:
                username = default_username

        agent_auth(t, username)
        if not t.is_authenticated():
            manual_auth(username, hostname, t, login_info)
        if not t.is_authenticated():
            print('*** Authentication failed. :(')
            t.close()
            sys.exit(1)

        chan = t.open_session()
        chan.get_pty()
        chan.invoke_shell()
        print('*** Here we go!\n')
        interactive.interactive_shell(chan, user_profile_obj, bind_host_obj)
        chan.close()
        t.close()

    except Exception as e:
        print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
        traceback.print_exc()
        try:
            t.close()
        except:
            pass
        sys.exit(1)
Exemple #32
0
    def startConnection(self):
        try:
            self.transport = paramiko.Transport(self.sock)

            try:
                self.transport.start_client()
            except paramiko.SSHException:
                os.write(sys.stdout.fileno(), '\033[91m*** SSH negotiation failed.\n\033[0m')
                sys.exit(1)

            try:
                keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
            except IOError:
                try:
                    keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
                except IOError:
                    # os.write(sys.stdout.fileno(), '*** Unable to open host keys file\n')
                    keys = {}

            # check server's host key -- this is important.
            key = self.transport.get_remote_server_key()

            if self.credentials['hostname'] not in keys:
                # os.write(sys.stdout.fileno(), '*** WARNING: Unknown host key!\n')
                pass
            elif key.get_name() not in keys[self.credentials['hostname']]:
                # os.write(sys.stdout.fileno(), '*** WARNING: Unknown host key!\n')
                pass
            elif keys[self.credentials['hostname']][key.get_name()] != key:
                # os.write(sys.stdout.fileno(), '*** WARNING: Host key has changed!!!\n')
                sys.exit(1)
            else:
                # os.write(sys.stdout.fileno(), '*** Host key OK.\n')
                pass

            # get username
            if self.credentials['username'] == '':
                default_username = getpass.getuser()
                os.write(sys.stdout.fileno(), '\t\t\t\033[94mUsername [%s]: \033[0m' % default_username)
                self.credentials['username'] = input()

                if len(self.credentials['username']) == 0:
                    self.credentials['username'] = default_username

            self.agent_auth(self.transport, self.credentials['username'])
            if not self.transport.is_authenticated():
                self.manual_auth(self.credentials['username'], self.credentials['hostname'])
                os.system('clear')
            if not self.transport.is_authenticated():
                os.write(sys.stdout.fileno(), '\t\t\t\033[91m*** Authentication failed. ***\n\033[0m')
                self.transport.close()
                sys.exit(1)

            chan = self.transport.open_session()
            chan.get_pty()
            chan.invoke_shell()

            self.interactive_shell(chan)
            chan.close()
            self.transport.close()

        except Exception as e:
            os.write(sys.stdout.fileno(), '\033[91m*** Caught exception: ' + str(e.__class__) + ': ' + str(e) + '\n\033[0m')
            traceback.print_exc()
            try:
                self.transport.close()
            except:
                pass
            sys.exit(1)
Exemple #33
0
        print("*** Caught exception: %s: %s" % (e.__class__, e))
        traceback.print_exc()
        try:
            t.close()
        except:
            pass
        sys.exit(1)


if __name__ == "__main__":
    ssh_user = ""
    ssh_port = 22
    if len(sys.argv) > 1:
        ssh_host = sys.argv[1]
    else:
        ssh_host = input("Hostname [[email protected]:22] > ")
    if ssh_host.find("@") >= 0:
        ssh_user, ssh_host = ssh_host.split("@")

    if len(ssh_host) == 0:
        print("*** Hostname required.")
        sys.exit(1)

    if ssh_host.find(":") >= 0:
        ssh_host, ssh_port_str = ssh_host.split(":")
        ssh_port = int(ssh_port_str)

    # get username
    if ssh_user == "":
        default_username = getpass.getuser()
        ssh_user = input("Username [%s]: " % default_username)
Exemple #34
0
# setup logging
paramiko.util.log_to_file('demo_sftp.log')

# Paramiko client configuration
UseGSSAPI = True             # enable GSS-API / SSPI authentication
DoGSSAPIKeyExchange = True
Port = 22

# get hostname
username = ''
if len(sys.argv) > 1:
    hostname = sys.argv[1]
    if hostname.find('@') >= 0:
        username, hostname = hostname.split('@')
else:
    hostname = input('Hostname: ')
if len(hostname) == 0:
    print('*** Hostname required.')
    sys.exit(1)

if hostname.find(':') >= 0:
    hostname, portstr = hostname.split(':')
    Port = int(portstr)


# get username
if username == '':
    default_username = getpass.getuser()
    username = input('Username [%s]: ' % default_username)
    if len(username) == 0:
        username = default_username
Exemple #35
0
    X_password=Mysql_sql.MysqlHelper().In_sql(sql)
    print('\033[3;31;40m'+'添加成功!\n'+'\033[0m')
def Add_competence(Uid,Sid):
    sql="insert into competence(user_id,server_id) values('%s','%s');"%(Uid,Sid)
    Acompetence=Mysql_sql.MysqlHelper().In_sql(sql)
    print('\033[3;31;40m'+'添加成功!\n'+'\033[0m')
def Del_competence(Uid,Sid):
    sql="delete from competence where user_id='%s' and server_id='%s';"%(Uid,Sid)
    Acompetence=Mysql_sql.MysqlHelper().In_sql(sql)
    print('\033[3;31;40m'+'删除成功!\n'+'\033[0m')

while True:
    try:
        os.system('clear')
        while True:
            User_name = input('Please enter your user :'******'不得为空')
                continue
            Pass_wd = input('Please enter your password :'******'不得为空')
                continue
            os.system('clear')
            if login(User_name,Pass_wd) ==False:
                break
        while True:
            HQ = Mysql_sql.MysqlHelper()
            #print HQ.IP_lite(User_name)
            List=HQ.IP_lite(User_name)
            while True: