Skip to content

Instantly share code, notes, and snippets.

@ostechnix
Created November 2, 2023 12:25
Show Gist options
  • Select an option

  • Save ostechnix/2c053aba072c3f201f32c22b60cdf9a6 to your computer and use it in GitHub Desktop.

Select an option

Save ostechnix/2c053aba072c3f201f32c22b60cdf9a6 to your computer and use it in GitHub Desktop.
A Bash Script to Assign IP Address to a Remote Linux System via SSH using nmcli Command.
#!/usr/bin/env bash
# ------------------------------------------------------------------
# Script Name: nmcli_remote_ip_changer.sh
# Description: A Bash Script to Assign IP Address to a
# Remote Linux System via SSH using nmcli Command.
# Website: https://gist.github.com/ostechnix
# Version: 1.0
# Usage: chmod +x nmcli_remote_ip_changer.sh
# ./nmcli_remote_ip_changer.sh
# ------------------------------------------------------------------
# Ask for the remote user and IP address of the machine
read -rp "Enter the remote username: " remote_user
read -rp "Enter the remote host IP address: " remote_host
# Connect to the remote machine and get the list of network connections
echo "Fetching list of network connections from the remote system..."
ssh "${remote_user}@${remote_host}" 'nmcli connection show'
# Prompt the user to choose a network connection
echo ""
read -rp "Enter the NAME of the connection you want to modify: " connection_name
# Ask for the new IP address to assign to this connection
read -rp "Enter the new IP address (in CIDR format, e.g., 192.168.1.10/24): " new_ip
read -rp "Enter the new Gateway (leave empty if unchanged): " new_gw
read -rp "Enter the new DNS (leave empty if unchanged, space separated for multiple): " new_dns
# Modifying the network connection using nmcli command
nmcli_modify_cmd="sudo nmcli connection modify \"${connection_name}\" ipv4.addresses ${new_ip} ipv4.method manual"
[ -n "$new_gw" ] && nmcli_modify_cmd+=" ipv4.gateway ${new_gw}"
[ -n "$new_dns" ] && nmcli_modify_cmd+=" ipv4.dns ${new_dns}"
# Command to restart NetworkManager service
nmcli_restart_cmd="sudo systemctl restart NetworkManager"
# Apply new IP address and restart NetworkManager
ssh -t "${remote_user}@${remote_host}" "
echo 'Applying the new IP address...'
${nmcli_modify_cmd} && echo 'IP address applied successfully.' || echo 'Failed to apply the new IP address.'
echo 'Restarting NetworkManager to apply changes...'
${nmcli_restart_cmd} && echo 'NetworkManager restarted successfully.' || echo 'Failed to restart NetworkManager.'
echo 'Please verify the connectivity to the remote system.'
"
@ostechnix
Copy link
Author

Assign new IP address to a remote Linux system using nmcli_ip_changer script:
Assign IP Address to a Remote Linux System via SSH using nmcli_remote_ip_changer Script

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment