Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Tutorial https://www.youtube.com/watch?v=Rf3-xc9JHgI&feature=youtu.be
- # импортируем библиотеки
- import paramiko
- import time
- # собираем данные для ввода
- while True:
- host = input("Enter server IP: ")
- user = input("Enter server admin user name: ")
- secret = input("Enter server admin password: ")
- port = input("Enter server port: ")
- script_name = input("Enter new script name: ")
- new_user = input("Enter new user name: ")
- new_user_pass = input("Enter new user password: ")
- script_file_name = input("Enter file to upload: ")
- print("Your input: ",host,user,secret,port,script_name,new_user,new_user_pass,script_file_name)
- check = input("If correct type 'y', esle type any key:" )
- if check == "y":
- break
- # подключаемся к серверу под админом
- client = paramiko.SSHClient()
- client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- client.connect(hostname=host, username=user, password=secret, port=port)
- ssh = client.invoke_shell()
- time.sleep(2)
- out = ssh.recv(60000)
- name = str(out[-16:]) # получаем имя сервера и админа
- def service(): # собираем сервис
- transport = paramiko.Transport((host, int(port)))
- transport.connect(username=user, password=secret)
- sftp = paramiko.SFTPClient.from_transport(transport)
- output = open("{}.service".format(script_name), 'w') # перезаписываем новые даные в файл конфига
- print("[Unit]", file=output)
- print("Description=My {}".format(script_name), file=output)
- print("After=network.target", file=output)
- print("[Service]", file=output)
- print("User={}".format(new_user), file=output)
- print("Group={}".format(new_user), file=output)
- print("Restart=on-failure", file=output)
- print("RestartSec=3", file=output)
- print("WorkingDirectory=/home/{}/".format(new_user), file=output)
- print('Environment="PYTHONPATH=/home/{}/"'.format(new_user), file=output)
- print("ExecStart=/home/{}/.venv/bin/python /home/{}/{}".format(new_user, new_user, script_file_name), file=output)
- print("[Install]", file=output)
- print("WantedBy=multi-user.target", file=output)
- output.close() # закрываем файл
- remotepath_ser = "/etc/systemd/system/{}.service".format(script_name)
- localpath_ser = "{}.service".format(script_name)
- sftp.put(localpath_ser, remotepath_ser)
- sftp.close()
- transport.close()
- client.close()
- def command(comm): # выполняем команду, проверяя закончилось ли её выполнение
- ssh.send(comm + "\n")
- time.sleep(1)
- while True:
- out = ssh.recv(60000)
- if str(out[-16:]) == name:
- break
- else:
- print("Wait fo it!")
- time.sleep(5)
- command("sudo su")
- command("apt update") # обновлемся
- print("updating")
- command("apt install -y git build-essential libssl-dev libffi-dev python3-pip python3-dev python3-setuptools python3-venv") # устанавливаем питон и необходимые библиотеки
- print("packs installed")
- time.sleep(1)
- # создаем нового пользователя
- ssh.send("adduser {}".format(new_user) + "\n")
- time.sleep(1)
- ssh.send(new_user_pass + "\n")
- time.sleep(1)
- ssh.send(new_user_pass + "\n")
- time.sleep(1)
- i = 0
- while i < 5:
- ssh.send("" + "\n")
- i = i + 1
- time.sleep(1)
- ssh.send("y" + "\n")
- time.sleep(1)
- print("user created")
- client.close()
- service() # загружаем сервис на сервер
- print("service uploaded")
- # загружаем на сервер файлы скрипта и требований
- transport = paramiko.Transport((host, int(port)))
- transport.connect(username=new_user, password=new_user_pass)
- sftp = paramiko.SFTPClient.from_transport(transport)
- remotepath = '/home/{}/{}'.format(new_user, script_file_name)
- localpath = script_file_name
- remotepath_req = '/home/{}/requirements.txt'.format(new_user)
- localpath_req = 'requirements.txt'
- sftp.put(localpath, remotepath)
- sftp.put(localpath_req, remotepath_req)
- sftp.close()
- transport.close()
- client.close()
- print("files uploded")
- # входим на сервер под новым пользователем
- client.connect(hostname=host, username=new_user, password=new_user_pass, port=port)
- ssh = client.invoke_shell()
- ssh.send("python3 -m venv .venv" + "\n") # разворачиваем виртуальное окружение
- time.sleep(1)
- print("venv created")
- ssh.send("source /home/{}/.venv/bin/activate".format(new_user) + "\n") # активируем виртуальное окружение
- out = ssh.recv(60000)
- time.sleep(1)
- print("venv activated")
- ssh.send("pip install -r /home/tst08/requirements.txt && deactivate" + "\n") # устанавливаем библиотеки из файл с требованиями
- out = ssh.recv(60000)
- time.sleep(3)
- print("requirements installed")
- client.close()
- # заходим на сервер под админом
- client.connect(hostname=host, username=user, password=secret, port=port)
- ssh = client.invoke_shell()
- ssh.send("systemctl daemon-reload" + "\n") # перезапускаем демона сервисов
- time.sleep(1)
- print("trying to start service")
- ssh.send("sudo systemctl start {}".format(script_name) + "\n") # запускам новый сервис
- time.sleep(1)
- ssh.send(secret + "\n")
- print("service started")
- time.sleep(1)
- client.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement