ich bin zwar seit über 15 Jahren Informatiker, aber ein totaler Programmier-Neuling und möchte Folgendes erreichen:
Ich möchte ein Programm schreiben, welches sich auf verschiedenen Rechnern über SSH anmeldet, dort ein paar Befehle ausführt und das Ganze protokolliert.
Für einen Rechner (mit dem ganzen Code in einer Python Datei) funktioniert das schon recht gut, allerdings möchte ich die Zielrechner und die auszuführenden Befehle aus einer separaten Datei auslesen und habe aktuell mühe, die Befehle so einzulesen, dass diese korrekt ausgeführt werden.
Ich habe dazu folgende Dateien erstellt:
Hosts.txt (IP, Port)
Code: Alles auswählen
192.168.1.200,22
192.168.1.201,21021
192.168.2.10,21000
Code: Alles auswählen
hostname
cat /etc/hosts
ifconfig
Code: Alles auswählen
import paramiko
from datetime import datetime
now = datetime.now() # current date and time
timestamp = now.strftime("%m/%d/%Y, %H:%M:%S ")
def run_ssh(hostname, port, username, password, remote_commands):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, port=port, username=username, password=password)
for command in remote_commands:
stdin, stdout, stderr = ssh.exec_command(command)
with open(hostname + ".log", "a") as logfile:
logfile.write(timestamp + command + "\n")
for line in stdout.readlines():
with open(hostname + ".log", "a") as logfile:
logfile.write(timestamp + line)
print("Closing SSH Session")
ssh.close()
Code: Alles auswählen
import connect
import csv
with open("hosts.txt") as file:
reader = csv.reader(file)
targets = list(reader)
username = "user"
password = "password"
remote_commands = [
"hostname",
"cat /etc/hosts",
"ifconfig",
]
for address in targets:
hostname = (address[0])
port = (address[1])
print("Connecting to " + hostname + " on Port: " + port)
connect.run_ssh(hostname, port, username, password, remote_commands)
So funktioniert es mit den Befehlen. Die Frage ist nun, wie ich die Variable remote_commands aus der Datei commands.txt einlesen muss, damit das sich gleich verhält, wie mit
Code: Alles auswählen
remote_commands = [
"hostname",
"cat /etc/hosts",
"ifconfig",
]
Wenn ich das so versuche
Code: Alles auswählen
remote_commands=open("commands.txt","r")
print(remote_commands)
Code: Alles auswählen
<_io.TextIOWrapper name='commands.txt' mode='r' encoding='cp1252'>
Danke und schöne Grüsse aus Zürich