简体   繁体   中英

Re-use SSH agent in PowerShell

I found an article that shows how you can re-use an SSH agent across multiple command line windows. This is great, however I'm using PowerShell and absolutely suck at it.

Is there a way to get the same functionality from within my PowerShell profile?

Update

Here is a brief overview of the reference post.

Starting ssh-agent sets a bunch of environment variables.

SSH_AGENT_PID=1784
SSH_AUTH_SOCK=/tmp/ssh-QzfPveH696/agent.696

ssh-agent allows you to specify the socket filename. This is what the post suggests to put in your ~/.bashrc (not possible since I'm using PowerShell).

# If no SSH agent is already running, start one now. Re-use sockets so we never
# have to start more than one session.

export SSH_AUTH_SOCK=/home/fboender/.ssh-socket

ssh-add -l >/dev/null 2>&1
if [ $? = 2 ]; then
   # No ssh-agent running
   rm -rf $SSH_AUTH_SOCK
   ssh-agent -a $SSH_AUTH_SOCK >/tmp/.ssh-script
   source /tmp/.ssh-script
   echo $SSH_AGENT_PID > /home/fboender/.ssh-agent-pid
   rm /tmp/.ssh-script
fi

It sets the socket file, runs ssh-add , if not agent is running it cleans some things up and sets one.

So how can I get that into a PowerShell profile?

I know this question is super old now, but I've taken a crack at it anyway.

Assumptions:

1) ssh-agent.exe is the Mingw32 version.

2) ssh-agent.exe is in your powershell path.

        Function Start-SSHAgent{
    param(
        [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
        [string]$socketfile="/p/.ssh-socket",                       # Used as input to ssh-agent, which expects POSIX format paths
        [Parameter(Mandatory=$false)]
        [string]$pidFile="p:\.ssh-agent-pid"                        # Used as input to Out-File which expects Windows format paths
    )
    $env:SSH_AUTH_SOCK=$socketfile
    $agent_is_running = Get-Process | ? { $_.ProcessName -like "ssh-agent*"}
    if($agent_is_running -eq $null){
        $sshAgentOutput = ssh-agent -a $env:SSH_AUTH_SOCK
        $parse = Select-String -InputObject $sshAgentOutput -Pattern "(?m)SSH_AGENT_PID=(\d+)"
        $sshAgentPid = $parse.Matches[0].Groups[1].Value
        $sshAgentPid | Out-File $pidFile
        $env:SSH_AGENT_PID = $sshAgentPid
    }
}

Drop that into your profile.ps1 file, and then you can run Start-SSHAgent (or you can take it out of the function to have it always run as soon as powershell starts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM