skip to Main Content

I have couple servers with services on Ubuntu 22.04

  1. Local server addresses = [*.*.*.*, *.*.*.*, *.*.*.*]
  2. Services name = [my_service1.service,my_service2.service,my_service3.service]

How to check services status from python on one of servers? All servers are connected to a local network with each other.

2

Answers


  1. Chosen as BEST ANSWER

    I was able to connect to a remote server and get the service status value. Next, you need to find the line Active: and find out what the status of the service is.

    import os
    stream = os.system("sshpass -p '********' ssh root@*.*.*.*  'sudo systemctl status my_service'")
    print(stream)
    

  2. From what I understand, you’re trying to connect to a database on a server from other servers in your local network. In Python, you can use libraries like psycopg2 for PostgreSQL, mysql-connector-python for MySQL, or pyodbc for SQL Server to connect to your database.

    If you’re using MySQL, here’s a basic example of mysql-connector-python library:

    import mysql.connector
    
    def check_database(server_ips, db_name, user, password):
        status_dict = {}
        for server_ip in server_ips:
            try:
                conn = mysql.connector.connect(
                    host=server_ip,
                    database=db_name,
                    user=user,
                    password=password
                )
    
                cursor = conn.cursor()
    
                # Execute a query
                cursor.execute('SELECT VERSION()')
    
                # Fetch result
                db_version = cursor.fetchone()
    
                # Close communication with the server
                cursor.close()
                conn.close()
    
                status_dict[server_ip] = db_version
            except Exception as e:
                status_dict[server_ip] = str(e)
    
        return status_dict
    
    # Example usage:
    server_ips = ['your_server_ip1', 'your_server_ip2', 'your_server_ip3']
    db_name = 'your_db_name'
    user = 'your_username'
    password = 'your_password'
    print(check_database(server_ips, db_name, user, password))
    

    I’m assuming that your database server allows connections from your client servers and that the username and password provided have the necessary permissions to execute queries.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search