2019-03-11 03:18:02 +00:00
|
|
|
import git
|
|
|
|
import subprocess
|
|
|
|
import os
|
|
|
|
import ssh
|
|
|
|
|
|
|
|
|
|
|
|
class Key(ssh.SSH):
|
|
|
|
def __init__(self,hostname, path, user, password=None, ssh_key=False):
|
|
|
|
super().__init__(hostname=hostname, path=path, user=user, passwd=password, ssh_key=ssh_key)
|
|
|
|
self.connect(5)
|
|
|
|
self.pub_key = None
|
|
|
|
self.keygen = None
|
2019-03-13 17:06:15 +00:00
|
|
|
self.local_path = os.path.expanduser('~')
|
|
|
|
self.public_key_path = os.path.join(self.local_path, '.ssh', 'id_rsa.pub')
|
2019-03-11 10:58:59 +00:00
|
|
|
self.public_key = None
|
2019-03-11 03:18:02 +00:00
|
|
|
|
|
|
|
def add_key(self):
|
2019-03-12 09:31:29 +00:00
|
|
|
stdout, stderr = self.run("echo \"{0}\" >> ~/.ssh/authorized_keys".format(self.public_key))
|
|
|
|
return stdout
|
2019-03-11 03:18:02 +00:00
|
|
|
|
2019-03-11 10:58:59 +00:00
|
|
|
@staticmethod
|
|
|
|
def create_key():
|
2019-03-13 17:06:15 +00:00
|
|
|
if os.path.exists(os.path.join(os.path.expanduser('~'),".ssh","id_rsa.pub")):
|
|
|
|
os.remove(os.path.join(os.path.expanduser('~'),".ssh","id_rsa.pub"))
|
|
|
|
os.remove(os.path.join(os.path.expanduser('~'), ".ssh", "id_rsa"))
|
2019-03-12 09:31:29 +00:00
|
|
|
|
2019-03-13 17:06:15 +00:00
|
|
|
print("Key Path:","{0}".format(os.path.join(os.path.expanduser('~'),".ssh","id_rsa")))
|
2019-03-12 09:31:29 +00:00
|
|
|
ret_code = subprocess.Popen(["ssh-keygen", "-b 4096","-N ''", "-q",
|
2019-03-13 17:06:15 +00:00
|
|
|
"-f {0}".format(os.path.join(os.path.expanduser('~'),".ssh","id_rsa")),
|
|
|
|
], shell=False,
|
2019-03-13 19:28:18 +00:00
|
|
|
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
|
|
try:
|
|
|
|
stdout, stderr = ret_code.communicate(input=b"\ny\n", timeout=8)
|
|
|
|
except subprocess.TimeoutExpired:
|
|
|
|
ret_code.kill()
|
|
|
|
stdout, stderr = ret_code.communicate()
|
2019-03-12 09:31:29 +00:00
|
|
|
return stdout.decode("utf-8")
|
2019-03-11 03:18:02 +00:00
|
|
|
|
|
|
|
def get_key(self):
|
2019-03-11 10:58:59 +00:00
|
|
|
self.public_key = open(self.public_key_path, 'r').readline()
|
2019-03-12 09:31:29 +00:00
|
|
|
return self.public_key
|
2019-03-11 03:18:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
new_key = Key("compute.bktus.com", "/home/git", "git", "123456", ssh_key=False)
|
|
|
|
# new_key.create_key()
|
2019-03-11 10:58:59 +00:00
|
|
|
new_key.get_key()
|
|
|
|
print(new_key.public_key)
|
|
|
|
new_key.add_key()
|