Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Changes
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ next:
- add check_snclient_* / CHECK_SNCLIENT_* environment variables; the old check_nsc_web_* / CHECK_NSC_WEB_* variables are deprecated but still supported for backwards compatibility
- send client timeout as X-Snclient-Timeout header; the legacy X-Nsc-Web-Timeout header is still sent for backwards compatibility
- fix integer performance values being printed with fractions when using -f argument
- add -proxy flag and CHECK_SNCLIENT_PROXY environment variable

0.7.6 Fri Apr 10 16:12:37 CEST 2026
- minimum go version is now 1.26
Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ Description:
check_snclient is a REST client for the NSClient++/SNClient webserver for querying
and receiving check information over HTTP(S).
Version:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is this for?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gpineda@thinkpad-e15g2:~/Documents/gpineda-dev/check_snclient$ ./check_snclient --help
Usage:
  check_snclient [options] [query parameters]

Description:
  check_snclient is a REST client for the NSClient++/SNClient webserver for querying
  and receiving check information over HTTP(S).

Version:
  check_snclient v0.7.6

It was an initiative to realign the cli usage described in the readme with the actual output.
By copying the output directly in the documentation (maybe a to lazy approach to include the new proxy options.
Feel free to remove it since this depends on the compiled version.

check_snclient vX.Y.Z
Example:
connectivity check (parent service):
check_snclient -p "password" -u "https://<SERVER>:8443"
Expand All @@ -110,6 +113,7 @@ Options:
-a <api version> API version of SNClient/NSClient++ (legacy or 1) Default: legacy
-l <username> REST webserver login. Default: admin
-p <password> REST webserver password
-proxy <url> Proxy URL or "env" (see Go net/http proxy documentation)
-config <file> Path to config file
TLS/SSL Options:
Expand All @@ -121,6 +125,25 @@ TLS/SSL Options:
-tlshostname <string> Use this servername when verifying tls server name
-k Insecure mode - skip TLS verification
Environment Variables:
Command line options take predence over environment variables.
check_snclient_password REST webserver password
CHECK_SNCLIENT_PASSWORD
check_snclient_login REST webserver login
CHECK_SNCLIENT_LOGIN
check_snclient_timeout Connection timeout in seconds
Optional set timeout state: 0-3 or OK, WARNING, CRITICAL, UNKNOWN
(default timeout state is UNKNOWN)
CHECK_SNCLIENT_TIMEOUT
check_snclient_proxy Proxy URL or "env" (see Go net/http proxy documentation)
CHECK_SNCLIENT_PROXY
check_snclient_proxy_url
CHECK_SNCLIENT_PROXY_URL
The old check_nsc_web_* / CHECK_NSC_WEB_* variables are deprecated
but still supported for backwards compatibility.
Output Options:
-h Print help
-v Enable verbose output
Expand Down
49 changes: 49 additions & 0 deletions pkg/checksnclient/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ Options:
-a <api version> API version of SNClient/NSClient++ (legacy or 1) Default: legacy
-l <username> REST webserver login. Default: admin
-p <password> REST webserver password
-proxy <url> Proxy URL or "env" (see Go net/http proxy documentation)
-config <file> Path to config file
TLS/SSL Options:
Expand All @@ -95,6 +96,10 @@ Environment Variables:
Optional set timeout state: 0-3 or OK, WARNING, CRITICAL, UNKNOWN
(default timeout state is UNKNOWN)
CHECK_SNCLIENT_TIMEOUT
check_snclient_proxy Proxy URL or "env" (see Go net/http proxy documentation)
CHECK_SNCLIENT_PROXY
check_snclient_proxy_url
CHECK_SNCLIENT_PROXY_URL
The old check_nsc_web_* / CHECK_NSC_WEB_* variables are deprecated
but still supported for backwards compatibility.
Expand Down Expand Up @@ -193,6 +198,7 @@ type flagSet struct {
URL string
Login string
Password string
Proxy string
APIVersion string
Timeout string
ErrorExit string
Expand Down Expand Up @@ -472,6 +478,11 @@ func parseEnvironmentVariables(flags *flagSet, env []string) {
case "check_snclient_timeout", "CHECK_SNCLIENT_TIMEOUT",
"check_nsc_web_timeout", "CHECK_NSC_WEB_TIMEOUT":
flags.Timeout = value
case "check_snclient_proxy", "CHECK_SNCLIENT_PROXY",
"check_snclient_proxy_url", "CHECK_SNCLIENT_PROXY_URL",
"check_nsc_web_proxy", "CHECK_NSC_WEB_PROXY",
"check_nsc_web_proxy_url", "CHECK_NSC_WEB_PROXY_URL":
flags.Proxy = value
}
}
}
Expand All @@ -483,6 +494,7 @@ func parseFlagsAndEnvironment(osArgs, env []string, output io.Writer) (flags *fl
flagSet.StringVar(&flags.URL, "u", "", "SNClient URL, for example https://10.1.2.3:8443")
flagSet.StringVar(&flags.Login, "l", "admin", "SNClient webserver login")
flagSet.StringVar(&flags.Password, "p", "", "SNClient webserver password")
flagSet.StringVar(&flags.Proxy, "proxy", "", "Proxy URL or \"env\" (see Go net/http proxy documentation)")
flagSet.StringVar(&flags.APIVersion, "a", "legacy", "API version of SNClient (legacy or 1)")
flagSet.StringVar(&flags.Timeout, "t", "10:UNKNOWN", "Connection timeout in seconds")
flagSet.StringVar(&flags.ErrorExit, "e", "UNKNOWN", "Connection error exit code.")
Expand Down Expand Up @@ -735,8 +747,14 @@ func buildHTTPClient(output io.Writer, flags *flagSet, timeout time.Duration) (*
return nil, err
}

proxyFunc, err := getProxyFunc(flags.Proxy)
if err != nil {
return nil, err
}

hTransport := &http.Transport{
TLSClientConfig: tlsConfig,
Proxy: proxyFunc,
DialContext: (&net.Dialer{
Timeout: timeout,
}).DialContext,
Expand All @@ -752,6 +770,37 @@ func buildHTTPClient(output io.Writer, flags *flagSet, timeout time.Duration) (*
return hClient, nil
}

func getProxyFunc(proxyStr string) (func(*http.Request) (*url.URL, error), error) {
if proxyStr == "" || strings.EqualFold(proxyStr, "none") || strings.EqualFold(proxyStr, "direct") {
return nil, nil
}

if strings.EqualFold(proxyStr, "env") {
return http.ProxyFromEnvironment, nil
}

if !strings.Contains(proxyStr, "://") {
proxyStr = "http://" + proxyStr
}

proxyURL, err := url.Parse(proxyStr)
if err != nil {
return nil, fmt.Errorf("invalid proxy url: %s", err.Error())
}

if proxyURL.Host == "" {
return nil, fmt.Errorf("invalid proxy url: missing host")
}

switch proxyURL.Scheme {
case "http", "https", "socks5":
default:
return nil, fmt.Errorf("unsupported proxy scheme: %s (only http, https and socks5 are supported)", proxyURL.Scheme)
}

return http.ProxyURL(proxyURL), nil
}

func extractResult(output io.Writer, flags *flagSet, contents []byte) (*queryV1, error) {
queryResult := &queryV1{}
if flags.APIVersion == "1" {
Expand Down
102 changes: 102 additions & 0 deletions pkg/checksnclient/check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package checksnclient

import (
"bytes"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -66,21 +68,32 @@ func TestParseEnvironmentVariables(t *testing.T) {
"check_snclient_password=newpass",
"CHECK_SNCLIENT_LOGIN=newlogin",
"check_snclient_timeout=30",
"CHECK_SNCLIENT_PROXY=http://proxy:8080",
})
assert.Equal(t, "newpass", flags.Password)
assert.Equal(t, "newlogin", flags.Login)
assert.Equal(t, "30", flags.Timeout)
assert.Equal(t, "http://proxy:8080", flags.Proxy)

// The check_snclient_proxy_url alias.
flags = &flagSet{}
parseEnvironmentVariables(flags, []string{
"check_snclient_proxy_url=http://proxy-url:8080",
})
assert.Equal(t, "http://proxy-url:8080", flags.Proxy)

// The deprecated check_nsc_web_* names must keep working.
flags = &flagSet{}
parseEnvironmentVariables(flags, []string{
"check_nsc_web_password=oldpass",
"CHECK_NSC_WEB_LOGIN=oldlogin",
"check_nsc_web_timeout=60",
"check_nsc_web_proxy=http://oldproxy:8080",
})
assert.Equal(t, "oldpass", flags.Password)
assert.Equal(t, "oldlogin", flags.Login)
assert.Equal(t, "60", flags.Timeout)
assert.Equal(t, "http://oldproxy:8080", flags.Proxy)
}

func TestBuildRequestTimeoutHeader(t *testing.T) {
Expand All @@ -96,3 +109,92 @@ func TestBuildRequestTimeoutHeader(t *testing.T) {
assert.Equal(t, "5.00", req.Header.Get("X-Snclient-Timeout"))
assert.Equal(t, "5.00", req.Header.Get("X-Nsc-Web-Timeout"))
}

func TestGetProxyFunc(t *testing.T) {
dummyReq, _ := http.NewRequest(http.MethodGet, "http://target.example.com", http.NoBody)

// empty / none / direct
for _, val := range []string{"", "none", "NONE", "direct", "DIRECT"} {
fn, err := getProxyFunc(val)
require.NoError(t, err)
assert.Nil(t, fn)
}

// env
t.Setenv("HTTP_PROXY", "http://envproxy:8080")
fn, err := getProxyFunc("env")
require.NoError(t, err)
require.NotNil(t, fn)
proxyURL, err := fn(dummyReq)
require.NoError(t, err)
require.NotNil(t, proxyURL)
assert.Equal(t, "http://envproxy:8080", proxyURL.String())

// standard URL
fn, err = getProxyFunc("http://127.0.0.1:8080")
require.NoError(t, err)
require.NotNil(t, fn)
proxyURL, err = fn(dummyReq)
require.NoError(t, err)
assert.Equal(t, "http://127.0.0.1:8080", proxyURL.String())

// URL with credentials
fn, err = getProxyFunc("http://user:secret@127.0.0.1:8080")
require.NoError(t, err)
require.NotNil(t, fn)
proxyURL, err = fn(dummyReq)
require.NoError(t, err)
assert.Equal(t, "http://user:secret@127.0.0.1:8080", proxyURL.String())

// auto-prepend http://
fn, err = getProxyFunc("127.0.0.1:3128")
require.NoError(t, err)
require.NotNil(t, fn)
proxyURL, err = fn(dummyReq)
require.NoError(t, err)
assert.Equal(t, "http://127.0.0.1:3128", proxyURL.String())

// socks5
fn, err = getProxyFunc("socks5://127.0.0.1:1080")
require.NoError(t, err)
require.NotNil(t, fn)
proxyURL, err = fn(dummyReq)
require.NoError(t, err)
assert.Equal(t, "socks5://127.0.0.1:1080", proxyURL.String())

// unsupported scheme
_, err = getProxyFunc("ftp://127.0.0.1:21")
require.Error(t, err)
assert.Contains(t, err.Error(), "unsupported proxy scheme: ftp")

// missing host
_, err = getProxyFunc("http://")
require.Error(t, err)
assert.Contains(t, err.Error(), "missing host")
}

func TestCheckWithProxy(t *testing.T) {
ctx := t.Context()
buf := &bytes.Buffer{}

proxyHit := false
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
proxyHit = true
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"command":"check_cpu","result":0,"lines":[{"message":"OK - cpu 5%"}]}`))
}))
defer proxyServer.Close()

exitCode := Check(ctx, buf, []string{
"-u", "http://unreachable-host-example.test:8443",
"-p", "secret",
"-a", "1",
"-proxy", proxyServer.URL,
"check_cpu",
}, nil)

assert.True(t, proxyHit, "request must pass through proxy")
assert.Equal(t, 0, exitCode)
assert.Contains(t, buf.String(), "OK - cpu 5%")
}