From 32e304e8ad815655ea1f2cecd0a2129c1db1ac83 Mon Sep 17 00:00:00 2001 From: Saturneric Date: Mon, 11 Mar 2019 11:18:02 +0800 Subject: [PATCH] Fixed and Added. --- .idea/encodings.xml | 4 + .idea/giteasy.iml | 6 +- .idea/vcs.xml | 6 ++ .idea/workspace.xml | 196 +++++++++++++++++---------------------- bin/python | Bin 13620 -> 0 bytes bin/python3 | Bin 13620 -> 0 bytes git.py | 198 +++++++++++++++++++++++++++++++++++++++ keygen.py | 31 +++++++ server.py | 219 -------------------------------------------- ssh.py | 65 ++++++++----- 10 files changed, 370 insertions(+), 355 deletions(-) create mode 100644 .idea/encodings.xml create mode 100644 .idea/vcs.xml delete mode 100755 bin/python delete mode 100755 bin/python3 create mode 100644 git.py create mode 100644 keygen.py delete mode 100644 server.py diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..15a15b2 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/giteasy.iml b/.idea/giteasy.iml index 6711606..496be93 100644 --- a/.idea/giteasy.iml +++ b/.idea/giteasy.iml @@ -1,8 +1,10 @@ - - + + + + diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 182caa1..02116a9 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -1,7 +1,17 @@ - + + + + + + + + + + + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + @@ -137,6 +137,8 @@ + + @@ -152,7 +154,7 @@ - + - - - - - - - - - - - - @@ -239,31 +210,36 @@ + + - + + - + - - + + - - + + - + - + @@ -271,9 +247,6 @@ - - @@ -286,30 +259,29 @@ - + - - + + + + + + + + + - - - - - - + - + - - + + - - - - + diff --git a/bin/python b/bin/python deleted file mode 100755 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R#J?y_xV|arA diff --git a/bin/python3 b/bin/python3 deleted file mode 100755 index 41d2f67bf6582de5993b9eb42dea08a00f393deb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13620 zcmeHOZ){uD6~AU_8=x!+f0ph~sRe{(MT?WtZUHsJZsYPIoDiBc4Ip&$Vn5f07u$P& zP7~ImY;B}?skLZAXlRo_`!E4tW=%}XDlJs&L>Nebx=qV8HdSovUc~+hO{nSw-tXLZ zUu?e^gtU*lSGxC{-#O==d+&Mg_`|u+Z(RBN2iq76e1fsLs~BUg=*wFen`c3AjC~qi zL+5-ra&PpZ=;8ZGTHgZoupuHpYcS+|G&(+7ZzARg>t%9zhP^RtM|85_+%{%x;@sx< zckweg3{-E^VbBQIwI()Ki#gBRg~|Me$nWpxJ6(TCY2jgSLbLR@RSH~xJY|?U!-CB3 zuk&Wt-&tu-SZ>voY}#KuZ(Hfiu?_$A@q1hP`<2uau5ER`q2RobIiAiWcsi5J3S94R zd6&CCdgjy!`+c|?cckaKAf9V~WHeHv3A%o~=eR-X1w*6fig%7R5kTWSWAgm$)MVD= zIokqm>`zW-H6G{^-1)B86<6Pv)y{9r>?6Z#gLAw{hTVtjGneRokk08XFk8FWNug# zo$PNy|FAZW`JZo~{3K*S^zG=OLf#6Q>B&%H)=U6X`z$)`qw~Ozrx(Awr~PL~Z+_~< zXPQE{LDq`SuDeF`-5w?xS|`p+^ZdUPv`z}0bmINrhNp?{uAPnRX6T?{nz|Lr&DyDK zCUj@lm%F+{hb(={IG(j0%ZG-AyesKRLSu%NPiHfEGL>5QJiRsRH0}8_QX)`2BhEQ8 zo41Xrt^-{-Z+a5OXt$%&xh^8^^qjsRF+B&>R0LE6R0LE6R0LE6R0LE6R0LE6R0LE6 zR0LE6R0LE6R0LE6R0RGXB5*`2{v~oWG8P#f(N6uXd!YE9w%FH>Vz^c+l${GG?arTT zIb8;gEgI!m@vqKS6neGdd9C!d{m!e94-{7i=PNCz&yY>A5-VPE{y^eV|E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;~W1LlV);K>U7*)FVncM^q%+rXM#; SPgr+{Li@hdvv=R#J?y_xV|arA diff --git a/git.py b/git.py new file mode 100644 index 0000000..0058867 --- /dev/null +++ b/git.py @@ -0,0 +1,198 @@ +import re +import os +import ssh + + +class Git(ssh.SSH): + projects = {} + projects_list = [] + remotes = {} + + def __init__(self, hostname, path, user, passwd): + super().__init__(hostname, path, user, passwd) + self.base_path = [False] + self.connect(5) + self.local_path = None + self.fix_cmd = None + self.fix_name = None + self.git_user = None + self.git_email = None + + def global_init(self, git_user, git_email): + self.git_user = git_user + self.git_email = git_email + cmd = "git config --global user.email \"{0}\";".format(git_email) + cmd += "git config --global user.name \"{0}\";".format(git_user) + stdout, stderr = self.run(cmd) + if self.check_error(stderr): + print("Global setting successful.") + else: + print(stderr) + raise ValueError("Args Abnormal") + + def base_init(self): + stdout, stderr = self.run("ls {}".format(self.path)) + if self.check_error(stderr): + if "giteasy\n" in stdout: + print("Directory already found.") + else: + stdout, stderr = self.run("mkdir {0}/{1}".format(self.path, "giteasy")) + if self.check_error(stderr): + print("Create directory.") + else: + raise ValueError(stderr) + self.base_path = [True, "{0}/{1}".format(self.path, "giteasy")] + else: + raise ValueError("Home Path Abnormal") + + def create_project(self, name): + if self.base_path[0]: + stdout, stderr = self.run("mkdir {0}/{1}".format(self.base_path[1], name)) + if self.check_error(stderr): + print("Succeed In Making Directory.") + self.projects[name] = {"path": "{0}/{1}".format(self.base_path[1], name), "branch": []} + cmd = "cd {0};".format(self.projects[name]["path"]) + cmd += "git init;" + cmd += "touch ReadME.md;" + cmd += "git add *;" + cmd += "git commit --message=init;" + stdout, stderr = self.run(cmd) + if self.check_error(stderr): + print("Succeed In Getting Repository.") + else: + print(stderr) + raise ValueError("Target Path Abnormal") + else: + raise ValueError("Base Path Abnormal") + else: + raise UnboundLocalError("Init Base First") + + def init_project_local(self, name): + cmd = self.fix_cmd + cmd += "mkdir {0};".format(name) + cmd += "git init;" + cmd = "git config --global user.email \"{0}\";".format(self.git_email) + cmd += "git config --global user.name \"{0}\";".format(self.git_user) + os.popen(cmd) + + def update_projects(self): + if self.base_path[0]: + stdout, stderr = self.run("ls {0}".format(self.base_path[1])) + if self.check_error(stderr): + reform = re.compile("\w+") + for project in stdout: + print("PROJECT", project) + project_name = reform.match(project).string.strip('\n') + self.projects[project_name] = {"path": "{0}/{1}".format(self.base_path[1], project_name), + "branch": []} + else: + raise ValueError("Base Path Abnormal") + + self.list_projects() + + else: + raise UnboundLocalError("Init Base First") + + def list_projects(self): + for project in self.projects.keys(): + self.projects_list.append(project) + print(project) + + def set_local(self, path): + self.remotes = {} + self.local_path = path + os.chdir(self.local_path) + + def add_remote(self, name="origin"): + os.popen( + "git remote add {3} ssh://{0}@{1}:{2}/{4}/.git".format(self.user, self.hostname, self.base_path[1], name, + self.fix_name)) + self.remotes[name] = {"name": name, + "url": "ssh://{0}@{1}:{2}/{3}/.git".format(self.user, self.hostname, self.base_path[1], + self.fix_name)} + + def fetch_remote(self, name): + if name in self.remotes.keys(): + os.popen("git fetch {0}".format(name)) + + def get_remote(self): + ret_code = re.compile(r"[\t, ]") + for remote in os.popen("git remote -v").readlines(): + results = ret_code.split(remote) + for item in results: + if item[0] not in self.remotes.keys(): + self.remotes[item[0]] = {"name": item[0], "url": item[1]} + + def push_remote(self, name, branch): + if branch in self.projects[self.fix_name]["branch"] and name in self.remotes.keys(): + os.popen("git push {0} {1}".format(name, branch)) + else: + raise ValueError("Branch or Name Abnormal") + + def pull_remote(self, name, branch): + if name in self.remotes.keys(): + os.popen("git pull {0} {1}".format(name, branch)) + else: + raise ValueError("Remote Error") + + def fix(self, name): + if name in self.projects_list: + self.fix_name = name + stdout, stderr = self.run("cd {0}".format(self.projects[name]["path"])) + if self.check_error(stderr): + print("Fixed.") + self.fix_cmd = "cd {0}".format(self.projects[name]["path"]) + ";" + else: + raise ValueError("Project Path Abnormal") + + def commit(self, message): + if self.base_path[0]: + stdout, stderr = self.run(self.fix_cmd + "git commit --message={0}".format(message)) + if self.check_error(stderr): + print(stdout) + else: + raise ValueError(stderr) + else: + raise UnboundLocalError("Init Base First") + + def get_branch(self): + if self.base_path[0] and self.fix_name is None: + stdout, stderr = self.run(self.fix_cmd + "git branch") + if self.check_error(stderr): + reform = re.compile("\w+") + for branch in stdout: + branch_name = reform.search("*master").group().strip('\n') + self.projects[self.fix_name]["branch"].append(branch_name) + + if '*' in str(branch): + self.projects[self.fix_name]["active_branch"] = branch_name + else: + print(stderr) + raise ValueError("Command Error") + + def list_branch(self): + for project in self.projects.items(): + for branch in project[1]["branch"]: + if branch == project[1]["active_branch"]: + print("(*)", branch) + else: + print(" ", branch) + + +if __name__ == "__main__": + compute = Git("compute.bktus.com", "/home/git", "git", "123456") + compute.global_init(git_user="saturneric", git_email="eric.bktu@gmail.com") + compute.base_init() + # compute.create_project("lcs") + compute.update_projects() + compute.list_projects() + compute.fix("lcs") + + # compute.get_branch("lcs") + compute.set_local("C:/Users/Saturneric/Documents/Code/") + compute.init_project_local("test") + # compute.add_remote(); + # compute.get_remote() + # compute.get_branch() + # compute.list_branch() + print(compute.projects) diff --git a/keygen.py b/keygen.py new file mode 100644 index 0000000..4c4a1f4 --- /dev/null +++ b/keygen.py @@ -0,0 +1,31 @@ +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 + + def add_key(self): + self.run("echo \"{0}\" >> ~/.ssh/authorized_keys".format(self.pub_key)) + + def create_key(self): + ret_code = subprocess.Popen(["ssh-keygen", "-b 4096", "-t rsa"], shell=True, + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + stdout, stderr = ret_code.communicate(input=b"\ny \n \n \n") + self.get_key() + + def get_key(self): + self.pub_key = os.popen("cat ~/.ssh/id_rsa.pub").read() + + +if __name__ == "__main__": + new_key = Key("compute.bktus.com", "/home/git", "git", "123456", ssh_key=False) + # new_key.create_key() + # new_key.get_key() + # new_key.add_key() diff --git a/server.py b/server.py deleted file mode 100644 index 1649ced..0000000 --- a/server.py +++ /dev/null @@ -1,219 +0,0 @@ -import paramiko -import re -import os - -class ssh(object): - ssh = paramiko.SSHClient(); - def __init__(self, hostname, path, user, passwd=None, sshkey=False): - self.hostname = hostname; - self.path = path; - self.user = user; - self.sshkey = sshkey; - - if sshkey == True: - self.passwd = None; - self.key = paramiko.RSAKey.from_private_key_file('/Users/huyibing/.ssh/id_rsa') - else: - self.passwd = passwd; - - self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - - def close(self): - self.ssh.close(); - - def run(self, cmd): - print("CMD:", cmd) - stdin, stdout, stderr = self.ssh.exec_command(cmd) - - stdout = list(stdout); - stderr = list(stderr); - return stdout, stderr; - - def check_error(self, stderr): - if len(stderr) == 0: - return True - else: - return False - - def connect(self,timeout): - if self.sshkey: - self.ssh.connect(hostname=self.hostname, port=22, username=self.user, pkey=self.key, timeout=timeout); - else: - self.ssh.connect(hostname=self.hostname, port=22, username=self.user, password=self.passwd, timeout=timeout); - - def __del__(self): - self.close(); - -class git(ssh): - projects = {} - projects_list = [] - remotes = {} - fix_name = None; - - def __init__(self, hostname, path, user, passwd): - super().__init__(hostname, path, user, passwd); - self.base_path = [False]; - self.connect(5); - - - - def globalinit(self,git_user,git_email): - cmd = "git config --global user.email \"{0}\";".format(git_email); - cmd += "git config --global user.name \"{0}\";".format(git_user); - stdout, stderr = self.run(cmd) - if self.check_error(stderr): - print("Global setting successful.") - else: - print(stderr) - raise ValueError("Args Abnormal") - - - def baseinit(self): - stdout, stderr = self.run("ls {}".format(self.path)) - if self.check_error(stderr): - if "giteasy\n" in stdout: - print("Directory already found.") - else: - stdout, stderr = self.run("mkdir {0}/{1}".format(self.path, "giteasy")) - print("Create directory.") - self.base_path = [True,"{0}/{1}".format(self.path, "giteasy")] - else: - raise ValueError("Home Path Abnormal") - - def create_project(self,name): - if self.base_path[0]: - stdout, stderr = self.run("mkdir {0}/{1}".format(self.base_path[1],name)) - if self.check_error(stderr): - print("Succeed In Making Directory.") - self.projects[name] = {"path" : "{0}/{1}".format(self.base_path[1],name), "branch" : []} - cmd = "cd {0};".format(self.projects[name]["path"]); - cmd += "git init;"; - cmd += "touch ReadME.md;"; - cmd += "git add *;" - cmd += "git commit --message=init;"; - stdout, stderr = self.run(cmd) - if self.check_error(stderr): - print("Succeed In Getting Repository.") - else: - print(stderr) - raise ValueError("Target Path Abnormal") - else: - raise ValueError("Base Path Abnormal") - else: - raise UnboundLocalError("Init Base First") - - def update_projects(self): - if self.base_path[0]: - stdout, stderr = self.run("ls {0}".format(self.base_path[1])) - if self.check_error(stderr): - reform = re.compile("\w+") - for project in stdout: - print("PROJECT",project) - project_name = reform.match(project).string.strip('\n') - self.projects[project_name] = {"path" : "{0}/{1}".format(self.base_path[1],project_name), "branch" : []} - else: - raise ValueError("Base Path Abnormal") - - self.list_projects(); - - else: - raise UnboundLocalError("Init Base First") - - def list_projects(self): - for project in self.projects.keys(): - self.projects_list.append(project) - print(project) - - def set_local(self,path): - self.remotes = {}; - self.local_path = path; - os.chdir(self.local_path); - - def add_remote(self,name="origin"): - os.popen("git remote add {3} ssh://{0}@{1}:{2}/{4}/.git".format(self.user,self.hostname,self.base_path[1],name,self.fix_name)) - self.remotes[name] = {"name" : name, "url" : "ssh://{0}@{1}:{2}/{3}/.git".format(self.user,self.hostname,self.base_path[1],self.fix_name)} - - def fetch_remote(self,name): - if name in self.remotes.keys(): - os.popen("git fetch {0}".format(name)) - - def get_remote(self): - retcode = re.compile(r"[\t, ]") - for remote in os.popen("git remote -v").readlines(): - results = retcode.split(remote) - for item in results: - if item[0] not in self.remotes.keys(): - self.remotes[item[0]] = {"name":item[0],"url":item[1]} - - - - def push_remote(self,name,branch): - if branch in self.projects[self.fix_name]["branch"] and name in self.remotes.keys(): - os.popen("git push {0} {1}".format(name,branch)) - else: - raise ValueError("Branch or Name Abnormal") - - def pull_remote(self,name,branch): - if name in self.remotes.keys(): - os.popen("git pull {0} {1}".format(name,branch)) - else: - raise ValueError("Remote Error") - - - def fix(self,name): - if name in self.projects_list: - self.fix_name = name; - stdout, stderr = self.run("cd {0}".format(self.projects[name]["path"])) - if self.check_error(stderr): - print("Fixed.") - self.fix_cmd = "cd {0}".format(self.projects[name]["path"]) + ";"; - else: - raise ValueError("Project Path Abnormal") - - def commit(self,message): - if self.base_path[0]: - stdout, stderr = self.run(self.fix_cmd+"git commit --message={0}".format(message)) - else: - raise UnboundLocalError("Init Base First") - - def get_branch(self): - if self.base_path[0] and self.fix_name != None: - stdout, stderr = self.run(self.fix_cmd+"git branch") - if self.check_error(stderr): - reform = re.compile("\w+",) - for branch in stdout: - branch_name = reform.search("*master").group().strip('\n') - self.projects[self.fix_name]["branch"].append(branch_name) - - if '*' in str(branch): - self.projects[self.fix_name]["active_branch"] = branch_name - else: - print(stderr) - raise ValueError("Command Error") - - def list_branch(self): - for project in self.projects.items(): - for branch in project[1]["branch"]: - if branch == project[1]["active_branch"]: - print("(*)",branch) - else: - print(" ",branch) - - -if __name__ == "__main__": - compute = git("compute.bktus.com", "/home/git", "git", "123456") - compute.globalinit(git_user = "saturneric", git_email = "eric.bktu@gmail.com") - compute.baseinit(); - #compute.create_project("lcs") - compute.update_projects(); - compute.list_projects(); - compute.fix("lcs"); - - #compute.get_branch("lcs") - compute.set_local("/Users/huyibing/Documents/code/test") - #compute.add_remote(); - #compute.get_remote() - compute.get_branch(); - compute.list_branch(); - print(compute.projects) - diff --git a/ssh.py b/ssh.py index 72ce803..3bf1f4f 100644 --- a/ssh.py +++ b/ssh.py @@ -1,26 +1,47 @@ -import server -import subprocess -import os - -class key(server.ssh): - def __init__(self,hostname, path, user, passwd=None, sshkey=False): - super().__init__(hostname=hostname, path=path, user=user, passwd=passwd, sshkey=sshkey) - self.connect(5); - - def add_key(self): - self.run("echo \"{0}\" >> ~/.ssh/authorized_keys".format(self.pub_key)) - - def create_key(self): - retcode = subprocess.Popen(["ssh-keygen", "-b 4096", "-t rsa"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) - stdout, stderr = retcode.communicate(input=b"\ny \n \n \n") - - def get_key(self): - self.pub_key = os.popen("cat ~/.ssh/id_rsa.pub").read() +import paramiko +class SSH(object): + ssh = paramiko.SSHClient(); + def __init__(self, hostname, path, user, passwd=None, ssh_key=False): + self.hostname = hostname + self.path = path + self.user = user + self.ssh_key = ssh_key -newkey = key("compute.bktus.com", "/home/git", "git", "123456",sshkey=False); -#newkey.create_key(); -#newkey.get_key(); -#newkey.add_key(); \ No newline at end of file + if ssh_key: + self.passwd = None + self.key = paramiko.RSAKey.from_private_key_file('/Users/huyibing/.ssh/id_rsa') + else: + self.passwd = passwd + + self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + def close(self): + self.ssh.close() + + def run(self, cmd): + print("CMD:", cmd) + stdin, stdout, stderr = self.ssh.exec_command(cmd) + + stdout = list(stdout) + stderr = list(stderr) + return stdout, stderr + + @staticmethod + def check_error(stderr): + if len(stderr) == 0: + return True + else: + return False + + def connect(self, timeout): + if self.ssh_key: + self.ssh.connect(hostname=self.hostname, port=22, username=self.user, pkey=self.key, timeout=timeout) + else: + self.ssh.connect(hostname=self.hostname, port=22, username=self.user, password=self.passwd, + timeout=timeout) + + def __del__(self): + self.close()