-
Notifications
You must be signed in to change notification settings - Fork 1
/
manager.py
145 lines (122 loc) · 5.26 KB
/
manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import os
import paramiko
import telegram
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
# Replace with your own Telegram bot token
TOKEN = os.environ['Token']
# Initialize the SSH client
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to the server using provided credentials
state = None
def start(update, context):
global state
state = "CREDENTIALS"
update.message.reply_text(
"Please enter server credentials in the following format:\nserver_ip port username password")
def credentials(update, context):
global state
if state != "CREDENTIALS":
return
try:
# Parse the server credentials
credentials = update.message.text.split()
if len(credentials) != 4:
update.message.reply_text(
"Invalid number of credentials provided. Please enter server credentials in the following format:\nserver_ip port username password")
return
SERVER = credentials[0]
PORT = int(credentials[1])
USERNAME = credentials[2]
PASSWORD = credentials[3]
# Connect to the server
client.connect(SERVER, port=PORT, username=USERNAME, password=PASSWORD)
update.message.reply_text("Connected to server!")
state = "CONNECTED"
except Exception as e:
update.message.reply_text("Error connecting to server: " + str(e))
logging.basicConfig(filename="bot.log", level=logging.INFO)
def cmd(update, context):
global state
if state != "CONNECTED":
update.message.reply_text("Please connect to a server first using the /start command.")
return
command = " ".join(context.args)
try:
stdin, stdout, stderr = client.exec_command(command)
stdout.channel.recv_exit_status() # wait for command to complete
output = stdout.read().decode("utf-8")
update.message.reply_text(output)
logging.info(f"Command: {command} was executed successfully")
except Exception as e:
update.message.reply_text("Error executing command: " + str(e))
logging.error(f"Error executing command: {command}. Error: {e}")
# function to get a file from user and upload it to server
def upload(update, context):
global state
if state != "CONNECTED":
update.message.reply_text("Please connect to a server first using the /start command.")
return
if not context.args:
update.message.reply_text("Please provide the local path for the file.")
state = "UPLOAD_LOCAL"
return
local_path = context.args[0]
if not os.path.exists(local_path):
update.message.reply_text("Invalid local path. Please provide a valid local path.")
return
if state == "UPLOAD_LOCAL":
update.message.reply_text("Please provide the remote path for the file.")
state = "UPLOAD_REMOTE"
return
remote_path = context.args[0]
try:
sftp = client.open_sftp()
sftp.put(local_path, remote_path)
sftp.close()
update.message.reply_text(f"File was uploaded successfully.")
except Exception as e:
update.message.reply_text("Error uploading file: " + str(e))
# function to handle the /download command
def download(update, context):
global state
if state != "CONNECTED":
update.message.reply_text("Please connect to a server first using the /start command.")
return
remote_path = context.args[0]
try:
sftp = client.open_sftp()
if sftp.stat(remote_path):
file_name = remote_path.split("/")[-1]
sftp.get(remote_path, file_name)
with open(file_name, 'rb') as f:
update.message.reply_document(document=f, filename=file_name)
os.remove(file_name)
logging.info(f"File {remote_path} was downloaded and sent to user successfully.")
sftp.close()
else:
update.message.reply_text("Error the path is incorrect")
except Exception as e:
update.message.reply_text("Error downloading and sending file: " + str(e))
logging.error(f"Error downloading and sending file: {remote_path}. Error: {e}")
def stop(update, context):
global state
state = None
update.message.reply_text("Closing connection to server.")
client.close()
def help(update, context):
update.message.reply_text(
"Available commands:\n/start - Connect to a server\n/cmd [command] - Execute command on the server\n/upload [remote_path] - Upload a file to the server\n/download [remote_path] [local_path] - Download a file from the server\n/stop - Close the connection to the server\n/help - Display this message")
# Create the Updater and pass it your bot's token.
updater = Updater(TOKEN, use_context=True)
updater.dispatcher.add_handler(CommandHandler("start", start))
updater.dispatcher.add_handler(CommandHandler("cmd", cmd))
updater.dispatcher.add_handler(CommandHandler("upload", upload))
updater.dispatcher.add_handler(CommandHandler("download", download))
updater.dispatcher.add_handler(CommandHandler("stop", stop))
updater.dispatcher.add_handler(CommandHandler("help", help))
updater.dispatcher.add_handler(MessageHandler(Filters.text, credentials))
# Start the bot
updater.start_polling()
updater.idle()