- 1 year ago
Windows batch: Insert multiple lines into a remote Linux file at a specific location using PuTTY and sed
To insert multiple lines into a remote Linux file at a specific location using PuTTY and sed
through a Windows batch script, you can follow these steps:
Install PuTTY:
Download and install PuTTY from the official website: https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.htmlPrepare the text to be inserted:
Create a text file on your Windows system containing the lines you want to insert into the remote Linux file. Let's say the file is namedinsert_lines.txt
and contains the following lines:cssLine 1 to insert
Line 2 to insert
Line 3 to insert
Create a batch script:
Open a text editor and create a new batch script with a.bat
extension. Let's name itinsert_lines.bat
.Write the batch script:
In theinsert_lines.bat
script, add the following commands:batch@echo off
set REMOTE_HOST=your-remote-hostname-or-ip
set REMOTE_USER=your-remote-username
set REMOTE_PASSWORD=your-remote-password
set REMOTE_FILE=/path/to/remote/file
set TEMP_FILE=/tmp/temp_file.txt
echo. > %TEMP_FILE%
type insert_lines.txt >> %TEMP_FILE%
echo Opening PuTTY...
echo. | plink.exe -ssh %REMOTE_USER%@%REMOTE_HOST% -pw %REMOTE_PASSWORD% "sed '/<search-pattern>/r %TEMP_FILE%' %REMOTE_FILE% > %REMOTE_FILE%.tmp && mv %REMOTE_FILE%.tmp %REMOTE_FILE%"
echo Script execution completed.
pause
Replace the following placeholders in the script:
your-remote-hostname-or-ip
with the hostname or IP address of your remote Linux server.your-remote-username
with the username to connect to the remote server.your-remote-password
with the password for the remote user./path/to/remote/file
with the actual path to the remote file where you want to insert the lines.<search-pattern>
with a pattern or keyword that identifies the location in the remote file where you want to insert the lines. Make sure the pattern is unique and does not exist elsewhere in the file.
The script creates a temporary file on the local system, appends the lines from
insert_lines.txt
to the temporary file, and then usesplink.exe
(PuTTY's command-line tool) to connect to the remote server and execute thesed
command to insert the lines into the remote file at the specified location.Save and run the batch script:
Save theinsert_lines.bat
file and double-click it to run the script. It will open PuTTY, establish an SSH connection to the remote server, execute thesed
command, and insert the lines into the remote file.
Make sure you have PuTTY and plink.exe
in your system's PATH environment variable or provide the full path to the plink.exe
executable in the batch script.
Note: Ensure that you have the necessary permissions to modify the remote file. Use this script with caution, as it modifies files on a remote system. Test it on non-production systems before applying it to critical files.