Eric
Eric

Reputation: 24890

How to kill ssh-agent properly on Linux

I am using Git on Linux. When pushing to GitLab, sometimes it either stuck at:

debug1: Connecting to gitlab.com [52.167.219.168] port 22.

or

debug1: client_input_channel_req: channel 0 rtype [email protected] reply 1

debug3: send packet: type 100

It seems restarting Linux could solve it, but nobody likes to reboot machines, so I am trying to kill the ssh-agent process, then restart it.

The process is always defunct after kill, and then I can't use Git via SSH at all. Is there a way to restart the ssh-agent, or solve the issue described above without restarting the machine?

The SSH keys that I use include a key phrase, which I would input on first use of a SSH key.

The issue usually occurs after I bring the Linux desktop back from sleep, thus the network is reconnected, not sure whether this matters?

Again, does any one know how to kill or restart a ssh-agent agent, without making it become defunct?

Upvotes: 35

Views: 70765

Answers (5)

Eduard Mukans
Eduard Mukans

Reputation: 1015

You can kill ssh-agent by running:

ssh-agent -k

!NB, -k argument works only if $SSH_AGENT_PID environment variable is set. eval "$(ssh-agent -s)" sets the variable, but there're also other methods to start the agent without setting the environment variable. E.g., connecting to a remote server implicitly starts the agent without setting the variable. In this case, you need to use pidof ssh-agent or pgrep ssh-agent to find the ssh-agent PID and then kill it.

Upvotes: 32

iman
iman

Reputation: 22248

yes, ssh-agent might be defunct: [ssh-agent] <defunct>

trying to kill the agent could help:

eval "$(ssh-agent -k)"

but also try to check your keyring process (e.g. gnome-keyring-daemon), restart it or even remove the ssh socket file:

rm /run/user/$UID/keyring/ssh

Upvotes: 4

smac89
smac89

Reputation: 43098

Many ways:

  • killall ssh-agent
  • SSH_AGENT_PID="$(pidof ssh-agent)" ssh-agent -k
  • kill -9 $(pidof ssh-agent)

pidof is from the procps project. You may be able to find it for your distro if it is packaged

Upvotes: 9

wisbucky
wisbucky

Reputation: 37827

It shows defunct probably because its parent process is still monitoring it, so it's not removed from the process table. It's not a big deal, the process is killed. Just start a new ssh-agent:

eval $(ssh-agent)

ssh-add

Upvotes: 0

danglingpointer
danglingpointer

Reputation: 4920

You can try this bash script to terminate the SSH agent:

#!/bin/bash

## in .bash_profile

SSHAGENT=`which ssh-agent`
SSHAGENTARGS="-s"
if [ -z "$SSH_AUTH_SOCK" -a -x "$SSHAGENT" ]; then
    eval `$SSHAGENT $SSHAGENTARGS`
    trap "kill $SSH_AGENT_PID" 0
fi

## in .logout

if [ ${SSH_AGENT_PID+1} == 1 ]; then
    ssh-add -D
    ssh-agent -k > /dev/null 2>&1
    unset SSH_AGENT_PID
    unset SSH_AUTH_SOCK
fi

Upvotes: 6

Related Questions