To achieve this, you can use the paramiko
library in Python, which allows you to SSH into a server and execute commands. Below is the Python script that you can run on your local machine, which will SSH into the GCP instance, create a file named test.txt
in the home directory, and print “file created successfully”.
First, you need to install the paramiko
library if you haven’t already:
pip install paramiko
Then, you can use the following script:
import paramiko
# Define the server and login credentials
hostname = '10.127.8.74'
port = 22 # Default SSH port
username = 'your_username' # Replace with your username
password = 'your_password' # Replace with your password or use key authentication
# Create an SSH client
client = paramiko.SSHClient()
# Automatically add the server's host key (if missing) to the list of known hosts
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Connect to the server
client.connect(hostname, port, username, password)
# Execute the command to create the file
stdin, stdout, stderr = client.exec_command('touch ~/test.txt')
# Print the output and errors (if any)
print(stdout.read().decode())
print(stderr.read().decode())
print("file created successfully")
finally:
# Close the connection
client.close()
Explanation:
- paramiko.SSHClient(): Creates an SSH client.
- set_missing_host_key_policy(paramiko.AutoAddPolicy()): Adds the server’s host key to the known hosts automatically.
- connect(): Connects to the server using the provided hostname, port, username, and password.
- exec_command(): Executes the Linux command to create the file (
touch ~/test.txt
). - read().decode(): Reads and decodes the standard output and error.
- client.close(): Closes the SSH connection.
Note:
- Replace
your_username
andyour_password
with your actual username and password for the GCP instance. - If you’re using an SSH key for authentication instead of a password, you need to adjust the connection part as follows:
# Replace password-based connection with key-based
key_path = '/path/to/your/private/key' # e.g., ~/.ssh/id_rsa
key = paramiko.RSAKey(filename=key_path)
client.connect(hostname, port, username, pkey=key)
Save this script as, for example, create_file.py
, and run it from your local machine. It will SSH into the specified GCP instance and create a test.txt
file in the home directory.
I did try many times but not able to achieve the result.
Test is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.