SFTP using Powershell POSH-SSH

Install POSH-SSH module in PowerShell using command: REFERENCE

iex (New-Object Net.WebClient).DownloadString("https://gist.github.com/darkoperator/6152630/raw/c67de4f7cd780ba367cccbc2593f38d18ce6df89/instposhsshdev")

Example Output:

000581

Script:

Import-Module Posh-SSH #Load the Posh-SSH module

#Set the credentials
$Password = ConvertTo-SecureString 'Password' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('user', $Password)

#Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\Sumit\SFTP.txt"
$SftpPath = '/home/user/SFTP-TEST/'

#Set the IP of the SFTP server
$SftpIp = '10.10.10.10'

#Establish the SFTP connection
New-SFTPSession -ComputerName $SftpIp -Credential $Credential

#Upload the file to the SFTP path
Set-SFTPFile -SessionId 0 -LocalFile $FilePath -RemotePath $SftpPath

#Disconnect SFTP session
(Get-SFTPSession -SessionId 0).Disconnect()

Example script:

000583

Another Example for authentication using Private Key:

# Define Serve Name
$ComputerName = "10.10.10.10"

# Define UserName
$UserName = "user"

#Define the Private Key file path
$KeyFile = "C:\Users\sumit\MyPrivateKeyRSA\Key"
$nopasswd = new-object System.Security.SecureString

#Set Credetials to connect to server
$Credential = New-Object System.Management.Automation.PSCredential ($UserName, $nopasswd)

# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\Sumit\SFTP1.txt"
$SftpPath = 'data/'

#Command to connect to the server for SFTP
#New-SSHSession -ComputerName $ComputerName -Credential $Crendtial -KeyFile $KeyFile

# Establish the SFTP connection
$SFTPSession = New-SFTPSession -ComputerName $ComputerName -Credential $Credential -KeyFile $KeyFile

# Upload the file to the SFTP path
Set-SFTPFile -SessionId $SFTPSession.SessionID -LocalFile $FilePath -RemotePath $SftpPath

# Disconnect SFTP session
$SFTPSession.Disconnect()

Advertisements