
| Current Path : /var/www/web-klick.de/dsh/90_akt/resources/ |
Linux ift1.ift-informatik.de 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64 |
| Current File : /var/www/web-klick.de/dsh/90_akt/resources/ssh_helper.py |
__author__ = 'Dominik'
import os
import sys
from subprocess import Popen, PIPE
import shlex
from sys import exit
import fileinput
import getpass
on_windows = "nt" in os.name
def call_proc(command, to_console=False):
if to_console:
Popen(shlex.split(command), stdout=sys.stdout, stderr=sys.stdout).communicate()
return
res, err = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE).communicate()
if "\r\n" in res:
res = res.split("\r\n")
elif "\n" in res:
res = res.split("\n")
return res, err
def whereis(name):
if on_windows:
out, err = call_proc("where " + name)
out = out[0]
return out, err
else:
raise NotImplementedError("whereis: not implemented!")
def exit_err(message):
print(message)
exit()
def get_input(message, eval=False):
print(message)
return raw_input() if not eval else input()
def run_command(user, server, command, params="-o PasswordAuthentication=no -o StrictHostKeyChecking=no", to_console=False, user_message = ""):
if to_console: params=""
if not user_message == "": print(user_message)
return call_proc("ssh "+params+ " " +user+ "@" + server + " \"" + command + "\"", to_console)
def setup_ssh_key_authentication(user_path, user, server):
if not os.path.exists(user_path + ".ssh"):
os.mkdir(user_path + ".ssh", 0755)
if not os.path.isfile(user_path + ".ssh/id_rsa.pub"):
res, err = call_proc("ssh-keygen -b 1024 -N '' -f " + user_path + ".ssh/id_rsa -t rsa -q")
if "failed" in res + err:
return (False, "Unable to generate key pair!" + res + err)
pub_key, err = call_proc("cat " + user_path + ".ssh/id_rsa.pub")
if not "no such file" in pub_key.lower():
run_command(user, server, "mkdir ~/.ssh", to_console=True, user_message="Creating .ssh folder in case it doesn\'t exist..")
run_command(user, server, "echo \'" + pub_key + "\' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && chmod 700 ~/.ssh/ ", to_console=True, user_message="Transferring authorized keys to server and setting permissiosn")
else:
return (False, "Can\'t find public key, unable to fix this. Please make sure that you're public key is stored at " + user_path + ".ssh/id_rsa.pub and has proper read permissions")
if "n" in get_input("Would you like to continue? (If the connection failed, you might as well abort) [Y|n]").lower():
return (False, "Aborted by user")
os.chdir(user_path + ".ssh")
ret, err = run_command(user, server, "ls -la",user_message="trying to exec ls -la on the server")
if ".." in ret: return(True, "Successfully connected to the server")
else : return(False, "Connection to server couldn\'t be established!"+ret+err)
def check_pubkey_authentication():
res, err = call_proc(
"ssh -o PasswordAuthentication=no -o StrictHostKeyChecking=no" + user + "\@" + server + " ls -a")
return False if not ".." in res else True
def setup_check_connectivity(user, server, need_annex=False):
user_path = os.path.expanduser('~' + getpass.getuser() + "/").replace("\\", "/")
tools = ["git", "ssh-keygen", "ssh", "cat"]
if need_annex: tools.append("git-annex")
for tool in tools:
res, err = whereis(tool)
if not tool in res:
if not "n" in get_input(tool + " not found! You will need to install MSYS Git and adding its \"bin\" folder to PATH. Would you like download Git? [Y|n]").lower():
call_proc("start http://git-scm.com/download/win", True)
get_input("Continue when you've installed Git...")
return setup_check_connectivity(user, server)
return (False, tool + " not found! Aborting")
print("Checking ssh connectivity...")
message = "Unable to connect via public key. Would you like to transfer your public key to the server? [Y|n]"
res, err = call_proc(
"ssh -o PasswordAuthentication=no -o StrictHostKeyChecking=no " + user + "\@" + server + " \"ls -a\"")
if ".." in res:
return (True, "Connection Established")
if not os.path.isfile(user_path + ".ssh/id_rsa.pub"):
message = """SSH configuration folder not found or public key not found!
You'll need to generate a public & private key pair in your """ + user_path + """./ssh folder and configure your server to allow your public key!\n
Would you like to setup ssh (generate key pair and add public key to the hosts authorized_keys)? [Y|n]"""
if "n" in get_input(message).lower():
return (False, "Aborted by user")
return setup_ssh_key_authentication(user_path, user, server)
if __name__ == "__main__":
if len(sys.argv) > 2:
server = sys.argv[1]
user = sys.argv[2]
else:
print("ssh_helper.py [server user]")
server = get_input("Please enter the server address to which you wish to connect:")
user = get_input("finally the username which will be used to connect to the server:")
(success, message) = setup_check_connectivity(user, server)
if not success:
exit_err(message)
else:
print(message)
print("You may now connect to the server by just typing ssh " + user + "@" + server + ". You will be automatically authenticated by public key authentication")