密钥加密 - 18570580798/study GitHub Wiki

import os import platform import paramiko

class Decrypt:

def get_password_by_key(self, key):
    remote_cmd = os.getenv("ROBOT_DECRYPT_SHELL")
    if remote_cmd is None:
        remote_cmd = "curl -s localhost:8080/static/decrypt.sh|sh -s"
    cipher = ""

    # rf_common setenv
    ssh_hostname = os.getenv("ROBOT_DECRYPT_HOSTNAME")
    ssh_port = os.getenv("ROBOT_DECRYPT_PORT")   
    ssh_account = os.getenv("ROBOT_DECRYPT_ACCOUNT")  

    # jenkins setenv
    token = os.getenv("ROBOT_DECRYPT_TOKEN")
    
    # ssh_server
    key_file_path = os.getenv("ROBOT_PRIVATE_KEY")
    ciphers = os.getenv("ROBOT_CIPHER_LIST")
    if token is None:
        token = ""
    
    if key_file_path is None and "linux" in platform.system().lower():
        key_file_path = os.getenv("HOME") + "/.ssh/id_rsa"
    
    cipher_list = ciphers.split(":")
    
    for i,c in enumerate(cipher_list):
        tmp = c.split('=', 1)
        if tmp[0].lower() == str(key).lower():
            cipher = tmp[1]
            break
        if i+1 == len(cipher_list):
            raise Exception("No Such Key:%s In ROBOT_TEST_CIPHERS" % key)
        
    cipher=cipher.replace("+", "\+")
    full_remote_cmd = "%s '%s' '%s'" % (remote_cmd, cipher, token)
    password = self._execute_ssh_remote_command(ssh_hostname, ssh_port, ssh_account, key_file_path, full_remote_cmd)
    return password.strip()            

def _execute_ssh_remote_command(self, hostname, port, username, key_file_path, cmd):
    pkey = paramiko.RSAKey.from_private_key_file(key_file_path)  
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostname, int(port), username, pkey=pkey)
    stdin, stdout, stderr = s.exec_command(cmd)
    ret=stdout.read()
    s.close()
    if ret.startswith("Error:"):
        raise Exception("SSH " + ret)
    return ret