Untitled

 avatar
unknown
plain_text
2 years ago
1.9 kB
44
Indexable
import paramiko
import time
import sys

# Set the hostname or IP address of the server you want to SSH into
hostname = "ip"

# Set the username and password for the server
username = "root"
password = "pw"

# Set the commands to run on the server
command1 = "qm status 100 | grep -c running"
command2 = "qm shutdown 100"
command3 = "sleep 30 && qm start 102"
command4 = "qm shutdown 102"
command5 = "sleep 30 && qm start 100"

# Create an SSH client object
client = paramiko.SSHClient()

# Automatically add the server's host key (this is insecure and should only be done in a trusted environment)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to the server
print("Connecting to server...")
try:
    client.connect(hostname, username=username, password=password)
except Exception as e:
    print("Failed to connect to server: " + str(e))
    sys.exit()

# Run the first command on the server
print("Running command: " + command1)
stdin, stdout, stderr = client.exec_command(command1)
output = stdout.read().decode().strip()
print("Output: " + output)

# Check the output and run the appropriate command
if output == "1":
    print("Running command: " + command2)
    stdin, stdout, stderr = client.exec_command(command2)
    print("Shutdown complete.")
    print("Running command: " + command3)
    stdin, stdout, stderr = client.exec_command(command3)
    output = stdout.read().decode().strip()
    print("Output: " + output)
elif output == "0":
    print("Running command: " + command4)
    stdin, stdout, stderr = client.exec_command(command4)
    print("Shutdown complete.")
    print("Running command: " + command5)
    stdin, stdout, stderr = client.exec_command(command5)
    output = stdout.read().decode().strip()
    print("Output: " + output)
else:
    print("No action required.")

# Close the SSH client
client.close()

print("Script complete.")