output
stringlengths 9
26.3k
| input
stringlengths 26
29.8k
| instruction
stringlengths 14
159
|
---|---|---|
There is a command line option that suits your needs:
#!/usr/bin/env python3 -E-E
Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME, that might be set. |
I have a small python script
#!/usr/bin/env python3import some_python3_moduledef main():
# do stuffif __name__ == '__main__':
main()and cannot run this script with Python3, since ROS sets the PYTHONPATH variable to some version 2.7.-related locations, meaning Python 3 cannot find any modules in its dist-packages directory. I would like to override this behaviour without having to modify the outside envorinment. That is, I wish to unset PYTHONPATH, but only for this script, and preferably from within it, so that the shebang will still work.
Is this possible?
Not sure if this is better suited to superuser.com
| Avoid passing environment variable to python script |
You'll have to trick the interpretor into ignoring the exec line, and put the script contents normally in the file. Options include:Polyglot scripts, where the exec command is written so that it looks like comment or a string or similar to the actual interpretor. Examples:Node.js
Python
Perlfeed the script to the interpretor with the initial lines stripped offexample using bash and process substitution
GRUB's 40_custom, which goes the other way: it takes a script with a shebang and then prints it uninterpreted. |
From Glenn's reply:Read your execve(2) man page. The limitation on a single optional
argument is OS dependent. Linux treats all words after the interpreter
as one single argument
If you want to do this:
#! /path/to/interpreter arg1 arg2 arg3You should in fact do this
#!/bin/sh
exec /path/to/interpreter arg1 arg2 arg3 "$@"If I want to write a script which contains some code in the script language,:
#! /path/to/interpreter arg1 arg2 arg3<script content in the script language>according to Glenn's reply, I should instead write the script as:
#!/bin/sh
exec /path/to/interpreter arg1 arg2 arg3 "$@"Then where should I write <script content in the script langauge>? Since it is written in the script language but not in the shell language, so it can't be placed in the the shell script, correct? Where should I place it?
Thanks.
| How shall I allow more than one arguments to the interpreter in a shebang in a script |
A script without shebang is meant to be interpreted by a POSIX-compliant sh interpreter. That's actually the POSIX way to write POSIX scripts, POSIX doesn't specify shebangs, though in practice using shebangs is more portable / reliable, and here is a good example why.
The bash shell is such a POSIX sh interpreter. bash (some versions and in some custom builds and in some environments) is actually the only FLOSS shell that I know that has been certified as compliant when running as sh (not when running as bash).
When executing a shebang-less script, bash, when execve() returns ENOEXEC and after having checked that it doesn't look like a binary file, interprets it in a child of his, simulating an execution by attempting to reset its state to the default.
That means however that that script when run from bash is interpreted as a bash script instead of a POSIX sh script unless bash is running in POSIX mode itself (such as when invoked as sh itself).
$ cat a
alias uname='echo hi'
uname
$ zsh -c ./a
hi
$ sh ./a
hi
$ bash -c ./a
Linux
$ (exec -a sh bash -c ./a)
hiSee how a was interpreted as bash language (ignoring aliases) instead of the sh languages when invoked by bash.
~$ strace -qqfe execve bash -c ./a
execve("/usr/bin/bash", ["bash", "-c", "./a"], 0x7fff0081a820 /* 66 vars */) = 0
execve("./a", ["./a"], 0x55b18b3a4660 /* 66 vars */) = -1 ENOEXEC (Exec format error)
[pid 123559] execve("/usr/bin/uname", ["uname"], 0x55b18b3a4660 /* 66 vars */) = 0
Linux
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=123559, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---See how bash didn't execute sh to interpret the script.
The fact that you get that warning: execute_coproc: coproc [147878:COPROC] still exists is a bug whereby bash fails to reset its state properly.
In any case, coproc is not a sh keyword so doesn't have its place in a shebang-less script. coproc is from zsh (while coprocesses are from ksh), though bash's implementation is completely different, so you should have a #! /bin/bash - shebang here.
With bash ./inner.sh or with a shebang, there is a proper execution of a new interpreter instance, and execve() completely and correctly wipes the process memory.
|
outer.sh:
ls -l /proc/$$/exe
coproc cat
./inner.sh
kill $!inner.sh:
ls -l /proc/$$/exe
set | grep COPROC || echo No match found
coproc cat
kill $!When I run ./outer.sh, this gets printed:
lrwxrwxrwx 1 joe joe 0 Jun 16 22:47 /proc/147876/exe -> /bin/bash
lrwxrwxrwx 1 joe joe 0 Jun 16 22:47 /proc/147879/exe -> /bin/bash
No match found
./inner.sh: line 3: warning: execute_coproc: coproc [147878:COPROC] still existsSince COPROC and COPROC_PID aren't set in the child, how does it know about the one from the parent to be able to give me that warning?
Also, I discovered that if I add #!/bin/bash to the top of inner.sh, or if I call bash ./inner.sh instead of just ./inner.sh from outer.sh, then the warning goes away. Why does this change anything, since it's getting ran with a bash subprocess either way?
| How does bash know about its parent's coprocess in this situation, and why does a shebang line change it? |
Your hash bang must start with the leading forward slash /
#!bin/bash is almost certainly not a valid directory/file path and should be #!/bin/bash
If you're unsure that a shell exists, you could always use ls or something to ensure the path is correct, or a more portable way to write it would be:
#!/usr/bin/env bash
This will cause the system to automatically lookup the path of bash (or whatever interpreter you chose) via env and use the first one it finds.
|
I embarrassed myself a little here with a simple typo and a profound ignorance. Save yourself some grief: your hasbangs/shebangs must always have a leading /, such as #!/bin/bash
be precise
if you are working between host and guest (virtual) machine without copy-and-paste enabled, just stop. Typos will kill your code and your question, (which can p_ss people off). Figure out how to get copy-and-paste working, or work from the one machine. Manually retyping is folly.
be grateful. There are really quite helpful people here.
they're all linux, but different distros can have idiosyncrasies when it comes to shells and scripts. (This includes full and minimal versions of the distro). Check your shell (ps -p$$ -ocmd= worked for me source). Do you have to create directories manually (esp. in minimal distros)?
for me, because its the most applicable to most systems (i.e "portable"), I'm going to start my scripts with #!/usr/bin/env <SHELL>, where SHELL is bash, sh, or whatever. Lots of how-to websites just seem to say "always start your script with #!/bin/bash" with no explanation or caveat. Just not true.
Shellcheck. This tool may be quite helpful. (Credit - roaima)I cannot get scripts to run in a Lubuntu (Xenial) Minimal (+LXDE) VM with shebangs - without, they're fine.
Following advice in a previous post, I have made a very simple script, in 4 versions that differ only in the shebang:
echotest (no shebang line):
#blantantly simple test to figure out script problemsecho "this is working - type something for me to repeat it"
read input
echo $inputechotest-bin-bash
#!bin/bash#blantantly simple test to figure out script problemsecho "this is working - type something for me to repeat it"
read input
echo $inputand two more, corresponding to #!bin/dash and [EDIT: inserted "bin" in the following, in this text not the script] #!bin/sh.
These files are saved in ~/bin, a directory that I created manually after reading a forum somewhere.
Testing the scripts from there yields:
x@computer:~$ echotest
this is working - type something for me to repeat it
test1
test1i.e. it works without any shebang, but
x@computer:~$ echotest-bin-bash
bash: /home/x/bin/echotest-bin-bash: bin/bash: bad interpreter: No such file or directory
x@computer:~$ echotest-bin-dash
bash: /home/x/bin/echotest-bin-dash: bin/bash: bad interpreter: No such file or directory
x@computer:~$ echotest-bin-sh
bash: /home/x/bin/echotest-bin-sh: bin/sh: bad interpreter: No such file or directoryFurther,
x@computer:~$ ./echotest-bin-bash
bash: ./echotest-bin-bash: No such file or directoryTo test another recommendation I read on a forum/blog, I removed the scripts from ~/bin and tried them while saved in /usr/local/bin.
x@computer:~$ echotest
bash: /home/x/bin/echotest: No such file or directoryAnd the same for all the other variants.
However,
x@computer:~$ sudo /usr/local/bin/echotest
this is working - type something for me to repeat it
test
test(i.e. it works)
x@computer:~$ sudo /usr/local/bin/echotest-bin-bash
sudo: unable to execute /usr/local/bin/echotest-bin-bash: No such file or directory
HangupNote, all permissions have been granted with either chmod +x <filename> or more rarely, chmod 777 <filename>, and double-checked with ls -l /rele/vant/directory.
x@computer:~$ echo $PATH
/home/x/bin:/home/x/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binIn answer to a previous response on my first attempt at this question, Lubuntu Minimal shows these installed:
||/ Name Version Architecture Description
+++-==============-============-============-=================================
ii dash 0.5.8-2.1ubu amd64 POSIX-compliant shellii bash 4.3-14ubuntu amd64 GNU Bourne Again SHellUsing commands I do not fully understand, gleaned from forums:
x@computer:~$ file "$(type -P bash)" 2>/dev/null
/bin/bash: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=[redacted for the forum], strippedx@computer:~$ type -p bash
/bin/bash Murphy, if you're reading - I have no luck trying to call up bin/bash, getting a prompt. I don't know how and my search terms bring up too much off-target material.
Finally, I tested the functioning script (i.e. without the shebang), in a .desktop file, and it functioned perfectly (Exec=echotest).
Why don't the shebangs work? Equivalent scripts with the #!bin/bash work just fine in my Ubuntu Mate (Xenial) host.
I am sure this is a very basic error, but I'm stumped. This is my second ever script, so I am happy to be directed to relevant basic materials.
Thanks in advance
Edit
Thanks Jesse_b.
Edit1.1 - no, I'm wrong. #!/bin/bash does work. I have searched the terminal history and I cannot find that entry I referred to previously.
Also, #!/usr/bin/env bash works perfectly.
Edit 2
Thanks Murphy
Using a hashbang #!/bin/sh and #!/bin/bash work just fine.
Further
x@computer:~$ ls -l /bin/bash
-rwxr-xr-x 1 root root 1037528 May 16 2017 /bin/bashx@computer:~$ /usr/bin/env | grep bash
SHELL=/bin/bashx@computer::~$ ls -l /bin/*sh
-rwxr-xr-x 1 root root 1037528 May 16 2017 /bin/bash
-rwxr-xr-x 1 root root 154072 Feb 17 2016 /bin/dash
lrwxrwxrwx 1 root root 4 May 16 2017 /bin/rbash -> bash
lrwxrwxrwx 1 root root 4 Feb 17 2016 /bin/sh -> dashA final edit - different distros will be more or less strict on how your hashbangs/shebangs are formatted. I found this post wherein someone describes similar problems with an earlier versions of Mint/Xfce and Lubuntu/LXDE.
(I ran into troubles when I manually re-typed a script in my host Ubuntu Mate into a Lubuntu Minimal/LXDE guest. I thought I observed different behaviour between distros, but a) I didn't understand the significance of the shebang format, b) there are websites that offer maybe-not-so-good advice, and c) I am prone to typos. As an experiment, see if your script will work without a shebang at all.)
| cannot get scripts to run in a Lubuntu (Xenial) Minimal (+LXDE) VM with shebangs |
To take a look in all the detail of the shebang mechanism use the Mascheck page
In particular, the item about "Splitting arguments" and the table below to see the details for many different systems.
Also take a look at: "interpreter as #! script" to understand that not all systems allow one shebang to call some other shebang script.
If you need/require more detail, just ask.
|
Linux only supports one argument in a shebang line:
This:
#!/bin/sh
cat > pr_args <<'EOF'
#!/bin/sh -e
printf "'%s'\n" "$@"
EOFcat > shebang <<'EOF'
#!pr_args a b c
EOFchmod +x pr_args shebang./shebang A B Crm shebang pr_argsprints
'a b c'
'./shebang'
'A'
'B'
'C'Are there any Unices where I'll get
'a'
'b'
'c'
'./shebang'
'A'
'B'
'C'? What does Mac OS X do?
| Multiple arguments in shebang lines |
This happens when a file contains \r\n as a line terminator instead of \n, since \r is a C0 control code meaning "go to the beginning of the current line".
To fix, run dos2unix foo.py.
Example session:
ben@joyplim /tmp/cr % echo '#!/usr/bin/env python' > foo.py
ben@joyplim /tmp/cr % chmod +x foo.py
ben@joyplim /tmp/cr % ./foo.py
ben@joyplim /tmp/cr % unix2dos foo.py
unix2dos: converting file foo.py to DOS format ...
ben@joyplim /tmp/cr % ./foo.py
: No such file or directory
ben@joyplim /tmp/cr % ./foo.py 2>&1 | xxd
0000000: 2f75 7372 2f62 696e 2f65 6e76 3a20 7079 /usr/bin/env: py
0000010: 7468 6f6e 0d3a 204e 6f20 7375 6368 2066 thon.: No such f
0000020: 696c 6520 6f72 2064 6972 6563 746f 7279 ile or directory
0000030: 0a .Specifically note the 0d3a in the output.
| I'm having an issue where when I transfer a Python file to my VPS via FTP and try to run it using ./foo.py I am returned with the error: : No such file or directory.
The error seems to indicate that the file I am trying to execute does not exist. But I can run the program with no problems using python foo.py which leads me to believe that the error actually probably means something else.
At first I thought it could be an issue with the shebang line, so I copied all of the content of the file and pasted it into a new file on the VPS that had not been transferred via FTP. The two files had exactly the same content but when I ran the new file using ./bar.py it ran as expected.
So I've come to the conclusion that this could be an issue with the way that it is transferred. I have switched between ASCII and binary but both of these transfer methods give the same error.
Is it possible to stop this from happening?
| Why does trying to run a python executable return ': No such file or directory' after transferring it to server via FTP? [duplicate] |
If you make a script executable, the loader will treat the first line as an interpreter directive and use the specific program to run the script. In this case you are using the Korn Shell #!/bin/ksh or the Bourne Shell #!/bin/sh.
| Also what are the main differences between these two. To execute a script is it necessary to write this at the beginning of script?
| When to use #!/bin/ksh and #!/bin/sh? Need example [duplicate] |
You could write a shell script that removes the shebang line, if any, and passes the result to db. Place this script in a directory of your PATH. Otherwise you might have to specify the full path of the script in the shebang line. Use this script as the interpreter for your parameterfile.
Example script runparam to remove the first line if it is a shebang line:
#!/bin/sh
awk 'FNR>1 || ! /^#!/' "$@" | dbExample parameterfile:
#!/usr/bin/env runparam
filename
::
conditionsYou can run it as
./parameterfileIn this case the script can assume that there will always be a shebang line.
You could also call the script directly with a parameterfile in the same way as you would call db, but this has no advantage.
runparam parameterfile
runparam parameterfile1 parameterfile2 [...]
runparam < parameterfileIf you will never call runparam with a file that doesn't contain a shebang line, you can use tail instead of awk to unconditionally remove the first line. This might be faster.
#!/bin/sh
tail -n+2 | db |
I have a program to list database files.
It is called direkly from the shell like
db filenameto list the whole file, or like
db 'filename :: conditions'to list only selected elements ...Another way is to call it with a file, wich contains all parameters.
db < parameterfileThe content is like (quite the same as the content in '' above):
filename
::
conditionsNow I woud like do make such a file executable. So that i can call just ./parameterfile.
To use a shebang #!/usr/bin/env db failed, because # is not a comment sign, I think. I got the error message
db - Line 1 near ""#.//r" - " - syntax errorshell returned 26Is there a one-liner to do this?
| Make STDIN executable with shebang |
Yes, in this case.
Summary: The hash-bang line (also called "shebang" and other things) is only ever needed if it's in an executable script that is run without explicitly specifying its interpreter (just as when executing a binary executable file).
In the case of your code, you're explicitly running the script within the here-document with bash already. There's no need to add the hash-bang as it will be treated as a comment.
Since the here-document script seems to want to be executed with the -x option set (judging from #!/bin/bash -x), you will have to use set -x inside the here-document to get the same effect as if running the here-document as its own script, again, because the hash-bang is treated as a comment.
The hash-bang line is used when executing an executable text file. The line tells the system what interpreter to use to execute it, and optionally allows you to specify one argument to that interpreter (-x in your case).
You do need the hash-bang there if you're writing the here-document to a file that will later be used as a script. For example:
cat >myscript.sh <<<END_OF_SCRIPT
#!/bin/bash
# contents of script
# goes here
END_OF_SCRIPTSuch a file also has to be made executable (chmod +x myscript.sh). But again, if you were to explicitly execute that script with bash, for example through
$ bash ./myscript.shor
$ bash -x ./myscript.sh(or equivalently from within another script) then no hash-bang is needed, and the script would not have to be made executable.
It all comes down to how you would want to execute the script.
See also the Wikipedia entry for Shebang.
|
Is it true to conclude that when using a bash here-doc like bash << HEREDOC, then always and without exceptions, shebang lines like #!/bin/bash -x are redundant?
If I would have to bet, I would bet that yes, they will be redundant, and could only use us to organize the information, like a sign saying for new users "the following set of commands was originally executed from a traditional script, don't run them in one line with double ampersands or another similar way".
I wonder what the experts say - Is the bash shebang line really are totally redundant when using a here-doc?
| Bash here-documents and shebang lines |
Your shebang isn't a shebang. It's just a she, missing the bang:
#!/bin/bash Corrected example:
$ ./test.sh
BASH is: /bin/bash
actual shell is: /bin/bash
$ sudo ./test.sh
BASH is: /bin/bash
actual shell is: /bin/bash
$ cat ./test.sh
#!/bin/bash
echo "BASH is: $BASH"
echo "actual shell is: `readlink /proc/$$/exe`" |
Invoking a script using sudo ignores the shebang and runs the script in a different shell. To test, I created a script (test.sh) containing:
#/bin/bash
echo "BASH is: $BASH"
echo "actual shell is: `readlink /proc/$$/exe`"First, I invoke the script without sudo:
$ ./test.sh
BASH is: /bin/bash
actual shell is: /bin/bashThen, I invoke the script with sudo:
$ sudo ./test.sh
BASH is:
actual shell is: /bin/dashI would not have expected this. Is this normal behavior?
Note: I'm using Ubuntu (14.04), where the default shell /bin/sh is a symlink to dash.
| Invoking a script with sudo ignores the shebang |
When a script is executed with ./ the interpreter from the shebang line is invoked.
with source the current shell is used (source is a bash extension, so you have to be running bash)
with bash script.sh the bash shell in your PATH is invoked with the shellscript. | I have script with #!/bin/ksh in the first line.
When I try to execute this script (run ./myscript.sh) the error occurred:
-bash: ./myscript.sh: /bin/ksh: bad interpreter: No such file or directoryBut when I execute this script through source myscript.sh or bash myscript.sh command - script runs successfully.
Yes, ksh is not installed and it is correct to install this.
But I can't understand different behavior ./ and bash or source
| /bin/ksh: bad interpreter: No such file or directory [duplicate] |
It may be not obvious these days, when modern linux distributions are most common operating systems, but some time ago you could find not only variuous systems not having bash at all, but as I recall even one linux distribution, which in one of its versions had /bin/bash linked to some not Bourne-like shell.
Moving #!/bin/bash scripts from one system to another was annoying back then, so it was wiser to script in pure bourne shell without bashisms.
So portability was the main reason I guess. I still use #!/bin/sh if I am sure there won't be any bashisms in the script, although it's been at least ten years since there is nothing else than linux around me.
| I have to modify existing shell scripts and they start with
#!/bin/shWhat reason would someone use that on a system that also supports bash?
I am tempted to change it but I want to make sure there's not a reason I don't know of for this.
My current problem is with a string manipulation and using ${mystring:start:length} would be so easy in bash but not avail in sh.
| Why would anyone use sh instead of bash? [closed] |
If the file does not start with a "shebang" line, most shells will attempt to execute the lines in the file themselves.
| As far as I understand, to make kernel execve a non-ELF file, the file must be a script started with a she-bang #!, but I have a script run successfully without it, why does this happen?
xtricman‚öìArchVirtual‚è∫Ô∏è~ü§êls a.sh -l
-r-xr-xr-x 1 xtricman users 23 9Êúà 26 18:45 a.sh
xtricman‚öìArchVirtual‚è∫Ô∏è~ü§êcat a.sh
echo "FDHDSFHGFKJJHGO"
xtricman‚öìArchVirtual‚è∫Ô∏è~ü§ê./a.sh
FDHDSFHGFKJJHGOThis a.sh script doesn't contain a she-bang, so how does it run?
| Why does a script without she-bang can be run? [duplicate] |
Does the quote mean that if the script is executed in bash via command myscript, thenbash will first assume it is an ELF and calls execve() on it, and because it is a bash script not ELF, execve() call will fail,If Bash finds an executable file, it will first assume that it is in some format the operating system can execute and call execve on it. In the event that that succeeds, this still might not be an ELF or other native executable file. For example, Linux's binfmt_misc feature allows many other executable formats to run. In this particular case, the execve call will most likely fail.bash will next execute bash myscript?Bash will use its existing subprocess to execute the script within it, reinitialising the shell environment as necessary. There is not an additional process launched or exec call.Compared to running a bash script via bash myscript in bash, running the script via myscript in bash will additionally have a failure call to execve() on the script directly? Yes, I suppose so, if you mean "a failed call".If yes, is myscript slower than bash myscript? Why does "A Practical Guide to Linux Commands, Editors, and Shell Programming By Mark G. Sobell" say the opposite?Although you can use bash to execute a shell script, this technique causes the script to run more slowly than giving yourself execute permission and directly invoking the script.Mindful of prevailing libel laws, I won't comment on the second part of that question, but even several failed library & system calls are not going to make a measurable difference compared to the launch of an entire bash process and then interpreting a script. I can't access the page in question to find any context you might have missed out. It almost certainly isn't discussing the shebangless case, however.If a bash script myscript contains a shebang #! /bin/bash, when it is executed in bash via command myscript,is it executed in the same way as it is executed in bash via command bash myscript?Yes; in one case, bash myscript is execed directly by the subprocess, and in the other the system execs /bin/bash myscript once it finds the shebang line.is it executed in the same way as the shebang were removed from the script and then the script were executed via command myscript ?In so far as you can reasonably detect, yes. None of this matters. Strictly, the main() function of bash doesn't run again in this case, because the subprocess just reinitialises itself internally, and it does run in the other situation. You could construct a scenario where this matters if you were really keen, but it isn't worth the effort.Note that this is a Bash functionality, and other shells execute shebangless scripts with sh or some other shell, rather than either bash or themselves, as noted in the other question you linked. We're also assuming that your interactive shell is the same bash as the one in your shebang lines.
|
From bash manual:3.7.2 Command Search and Execution
After a command has been split into words, if it results in a simple
command and an optional list of arguments, the following actions are
taken.
...If the name is neither a shell function nor a builtin, and contains no slashes, Bash searches each element of $PATH for a directory
containing an executable file by that name.
If the search is successful, or if the command name contains one or more slashes, the shell executes the named program in a separate
execution environment. Argument 0 is set to the name given, and the
remaining arguments to the command are set to the arguments supplied,
if any.
If this execution fails because the file is not in executable format, and the file is not a directory, it is assumed to be a shell
script and the shell executes it as described in Section 3.8 [Shell
Scripts], page 39.Suppose a bash script myscript doesn't contain a shebang.Does the quote mean that if the script is executed in bash via command myscript, then bash will first assume it is an ELF and calls execve() on it, and because it is a bash script not ELF, execve() call will fail,
bash will next execute bash myscript?Compared to running a bash script via bash myscript in bash, running the script via myscript in bash will additionally have a
failure call to execve() on the script directly?
If yes, is myscript slower than bash myscript? Why does "A Practical Guide to Linux Commands, Editors, and Shell Programming By
Mark G. Sobell" say the opposite?Although you can use bash to execute a shell script, this technique causes the script to run more slowly than giving yourself
execute permission and directly invoking the script.If a bash script myscript contains a shebang #! /bin/bash, when
it is executed in bash via command myscript, is it executed in the same way as it is executed in bash via command bash myscript?
is it executed in the same way as the shebang were removed from the script and then the script were executed via command myscript
?Thanks.
My post is inspired by How is running a script like an executable different from running it by a shell explicitly? and Which shell interpreter runs a script with no shebang?
| How is a bash script executed via its filename as command name with and without shebang? |
I use this shebang, which allows for any packaged interpreter:
#!/usr/bin/env -S guix shell [--pure] [-m manifest.scm] [packages...] -- bash |
I want to write a script which executes within a specific guix shell environment. I'm hoping there's an equivalent version of the nix-shell shebang. For example, it would be cool to write something similar to the following:
#!guix shell
#!--manifest=manifest.scm bash# ... commands ...As a workaround, it may be sufficient to "source" the search paths of evaluating guix shell, e.g.:
#!/usr/bin/env basheval "$(guix shell --manifest=manifest.scm --search-paths)"# ... commands ... | Is there a Guix equivalent of nix-shell shebangs? |
The file-system where the script resides was mounted with 'NOEXEC' flag /dev/mapper/systemvg-home on /home type ext4 (rw,noexec,nosuid,nodev)
|
I have a python script, in which I have the following shebang #!/usr/bin/python
the script permissions are -rwxrwxrwx. 1 user user 709 script.py the owner of the script is the same as the user I use to run the script.
I do not understand why I get Permission denied when I run ./script.py but I can run it with python script.py or /usr/bin/python script.py. What I am missing?
Linux distribution is RedHat 6
| Python script shebang behavior |
I understand that a process can change its own name, but why isn't the name the same in both cases?Because the programs involved are not changing their own names. They are given the names that the default behaviour of Linux assigns. (Other operating systems behave differently, but this is a Linux question because it talks about /proc/*/comm files.)
On Linux, the program name in comm is taken from whatever the program image file name passed to execve() was. Note that this is not either the argument vector nor the environment vector, and the statement that this name is taken from the argument vector on Linux is erroneous.
The program image file names that the shell is actually passing are /usr/bin/python and /usr/bin/mirage, so python and mirage are what /proc/self/comm are initialized to. (comm is the basename of the program image filename, truncated/padded.)
The argument vector initializes what a process has in its /proc/self/cmdline and the environment vector initializes what it has in /proc/self/environ. So with these and /proc/self/comm, and presuming that a program does not alter them when it runs, you know all three of the pieces of information that were passed to execve() and thus exactly "how a process was originally launched" (although, strictly speaking, this is how the program was launched, as the process was launched with fork()).
Here is an example of those three pieces in action, using clearenv, setenv, and exec from the nosh toolset to set up a small environment and force argv[0] for the purposes of exposition:
% clearenv setenv 1THIS 'is the environment string' setenv 2COMPRISING 'all of the environment.' \
> exec -a 'This is argv[0].' /bin/sleep 100 &
[1] 15564
% for i in /proc/$\!/{comm,cmdline,environ} ; do printf "%s:" $i ; cat -v $i ; printf "\n" ; done
/proc/15564/comm:3/proc/15564/cmdline:This is argv[0].^@100^@
/proc/15564/environ:1THIS=is the environment string^@2COMPRISING=all of the environment.^@
%
And indeed those are exactly what the nosh toolset's exec command passed to execve() in order to run /bin/sleep. (The 3 is because exec uses the C library's fexecve() function, which internally uses program image filenames of the form /proc/self/fd/3.)
The program image file happening to be a script with a named interpreter and the #! magic number, causing substitution of that interpreter for the program image file and shifting of the argument vector, does not change what goes into comm. It remains whatever program image filename was originally given to execve(). Yes, Linux is inconsistent here, because it does change what goes into cmdline in such cases to be the effective final argument string.
Further readinghttps://unix.stackexchange.com/a/432681/5132
https://unix.stackexchange.com/a/438007/5132
https://unix.stackexchange.com/a/257568/5132
https://unix.stackexchange.com/a/392600/5132
Jonathan de Boyne Pollard (2018). "clearenv". Manual. nosh toolset. Softwares.
Jonathan de Boyne Pollard (2018). "setenv". Manual. nosh toolset. Softwares.
Jonathan de Boyne Pollard (2018). "exec". Manual. nosh toolset. Softwares. |
Summary
Using mirage as an example, a python program that begins with a shebang:
#!/usr/bin/python
...Looking at /proc/<pid>/comm or using pgrep, it appears like ...
... the process name is "mirage" when I call it via the shebang:
/usr/bin/mirage &... but is "python" when I call python explicitly:
/usr/bin/python /usr/bin/mirage &I understand that a process can change its own name, but why isn't the name the same in both cases?
Is there a generic way to know how a process was originally launched (using only /proc or grep information)?Details - shebang
/home/martin> /usr/bin/mirage &
[1] 22638/proc/<pid>/comm says it is "mirage"
/home/martin> cat /proc/22638/comm
miragepgrep finds it as "mirage" but not as "python"
/home/martin> pgrep -al mirage && echo "found" || echo "not found"
22638 /usr/bin/python /usr/bin/mirage
found/home/martin> pgrep -al python && echo "found" || echo "not found"
not foundDetails - python
/home/martin> /usr/bin/python /usr/bin/mirage &
[1] 21348/proc/<pid>/comm says it is "python"
/home/martin> cat /proc/21348/comm
pythonpgrep finds it as "python" but not as "mirage"
/home/martin> pgrep -al mirage && echo "found" || echo "not found"
not found/home/martin> pgrep -al python && echo "found" || echo "not found"
21348 /usr/bin/python /usr/bin/mirage
found | Why does shebang lead to a different process name than an explicit call? |
You can implement this in two steps using execve: ask the C library to ask the kernel to execute the target, and if that fails, try again with foobar. This is actually how shells commonly implement execution.
There are other exec family functions which will run shebang-less scripts with /bin/sh, but execve won’t.
What exactly happens when I execute a file in my shell? has a lot more detail on this topic.
|
I have a library - users are to create executable files, potentially with a hashbang to tell exec which executable to use. If they omit the hashbang, then I think most systems default to /bin/sh, I want to change that default.
So some files might start with:
#!/usr/bin/env foobarother files might start with:
#!/usr/bin/env perlor
#!/usr/bin/env rubyAnd in some cases, the user will omit the hashbang altogether. In that case, I will still execute the file directly, and I want to default to using the foobar executable.
In other words, I don't know what the hashbang will be in advance, and I want the default to be foobar instead of the default being /bin/sh, if there is no hashbang present.
I think the way to do what I am doing is to create an executable that can run exec first, and if that fails with a particular error message, then run the script indirectly with the foobar executable?
Something like this:
function run {
stdio=$("$1" 2>&1)
if [[ stdout/stderr matches a certain error message ]]; then
foobar $1
fi
}My question is - does anyone know what I am talking about - and does anyone know how I can default to a particular executable if no hashbang is present? Not that it's in theory less convenient to check if there is a hashbang, and more in theory more convenient just to run it?
| Change the default executable for file with potentially missing shebang |
You can add the range option to the socat listening address:
socat TCP-LISTEN:22,fork,range=8.8.8.8/32 TCP:192.168.0.15:5900Or you can add the tcpwrap=vnc_forward option and define global rules for that vnc_forward service as per hosts_access(5).
That won't stop the connections from reaching socat, but socat will ignore them (with a warning) if they don't come from 8.8.8.8.
|
socat TCP-LISTEN:22,fork TCP:192.168.0.15:5900How can I tell to socat, that port 22 is only trusted from the remote IP address 8.8.8.8, and it should not accept connections from other IP addresses? This is on a Linux server.
| Tell socat to listen to connections from a single IP address |
You must use fork option, which handle a connection in a child process, make the parent process attempt to handle more connections.
In first terminal:
$ socat - UNIX-LISTEN:/tmp/comm,forkIn second terminal:
$ socat UNIX-CONNECT:/tmp/comm -Press Ctrl+C in second terminal, switch to the first terminal and see your server is still running.
|
I'd like to redirect an applications input and output to a unix socket and connect to that socket from another session. What I'm doing so far is the following:
On the "server" side:
socat EXEC:"command" UNIX-LISTEN:/tmp/commAnd on the "client" side:
socat UNIX-CONNECT:/tmp/comm -It works pretty good, but as soon as the client-side socat terminates, the server terminates, too. But I'd like it to keep running and reconnect later... How do I accomplish that?
| Stop socat from terminating when other end closes |
I quite like tcpdump for recording network connections. You actually can use it for what you want to achieve. Instead of using the READLINE endpoint in your socat connection, make it listen to some port.
remote server with ssl
^
| (ssl-encrypted)
socat
| (not ssl-encrypted)
v
local port <-- run tcpdump here
^
|
socat
|
v
your terminalYou then use a second socat connection to connect to the local port, where the first socat is listening. This is unencrypted. And on this port you can run tcpdump.
$ # easiest to use a separate terminal window for each command
$ socat TCP-LISTEN:9000,reuseaddr openssl:host:port,cafile=some.ca
$ tcpdump -i lo -w /tmp/tcpdump.output port 9000
$ socat READLINE,history=$HOME/.socat.hist TCP:localhost:9000 |
Socat is great for interactively testing line based human readable protocols like HTTP or IMAP.
For example:
$ socat -d -d READLINE,history=$HOME/s.hist openssl:host:port,crnl,cafile=some.caFor better analyzing I need to capture such an interactive session - i.e. the bytes received and sent.
Just hardcopying the terminal output via e.g. tux is not enough, because client/server parts are not marked and characters like '\t' are lost/silently converted.
Using tcpdump to capture helps only for unencrypted connections.
Thus my question.
The answer does not have to be socat-based. If another tool is better suited for that use case I would like to read about it.
Bonus points for a solution wheretime stamps are recorded as well
one can chose between interleaved recording (client/server side) or logging to separate files | How to record an interactive socat TCP/TLS session? |
The problem is due to socat being bi-directional by default. It attempts to read its standard input which is /dev/null, it gets an EOF and exits.
The solution is to use the -u option:
ExecStart=/usr/bin/socat -u UDP-RECV:4321 STDOUTThis tells socat to run unidirectionally from UDP-RECV:4321 to STDOUT.
|
The following socat command-line works as expected when entered at a shell prompt:
# /usr/bin/socat UDP-RECV:4321 STDOUTIt listens on UDP port 4321 and writes everything received to standard output.
The following is an attempt at starting this command as a systemd service with the intention that it writes received data to the systemd journal (the default destination for a service's standard output):
# /etc/systemd/system/socat.service
[Service]
ExecStart=/usr/bin/socat UDP-RECV:4321 STDOUTHowever, socat exits immediately when this service is started:
Process: 7425 ExecStart=/usr/bin/socat UDP-RECV:4321 STDOUT (code=exited, status=0/SUCCESS)Researching the problem (running socat with -d -d -d -d) revals that it's getting an EOF on standard output:
N starting data transfer loop with FDs [5,5] and [1,1]
N socket 2 (fd 1) is at EOF
I close(5)
N exiting with status 0Is it possible to use socat as a systemd service?
| Can socat be started directly by systemd? |
I tried the steps below, which should work, but does not work on Mac (forwards port 20 UDP text messages to port 29), but you might want to try it anyway:cd /tmp
mkfifo backpipe
sudo nc -ulk 20 0<backpipe |sudo nc -ulk 29 | tee backpipe
On another terminal - test it with echo -n “this is a test” | sudo nc -4u -w1 localhost 20It's possible the usage is mangled or the fifo special file isn't working.
However, I found an "easier" way.Download a very small c program source file called: udp_redirect (click here to download it)
Compile it with gcc -w udp_redirect.c -o udp_redirect
Run it in background sudo ./udp_redirect 127.0.0.1 20 127.0.0.1 29 &
Set up a listener on port 29 to test it sudo nc -ul 29
On a second terminal, test it with echo “this is a test” | sudo nc -4u -w1 localhost 20This test sends UDP text messages to port 20, and watch the listener on port 29 in the first terminal print the messages. You can also set up a listener on port 20 and see NO messages are available, they are all forwarded (not duplicated) to port 29.
I say it's 'easier' because the udp_redirect binary has much easier usage, does not have the requirement for a special fifo file, does not require pipes, does not require the nc utility, and most importantly, it works!
|
On Mac OS X 10.9.5 I am running boot2docker and would like to temporarily forward a non-privileged UDP port 69 to port 69 of the boot2docker virtual machine. Virtualbox only supports forwarding privileged ports.
I've tried running socat like so:
socat UDP-LISTEN:69,fork,reuseaddr UDP:192.168.59.101:69It works just fine until I try to make a tftp connection and then it crashes with:
socat[32232] E bind(5, {LEN=16 AF=2 0.0.0.0:69}, 16): Address already in useChecking netstat -an doesn't show much open as far as UDP:
udp6 0 0 *.58669 *.*
udp4 0 0 *.58669 *.*The only related thing I could find on the web was not of much help.
How on Mac OS X what is what is a good way to 'mirror' UDP traffic from one port to another?
| How can I redirect all UDP traffic from one port to another on BSD / OS X? |
I suspect your problem is more because whatever sends the UDP packets is not adding a newline character the commands (as in they should send "play\n" and not just "play").
In any case, if you want a new TCP connection to be created for each of the UDP packets, you should use udp-recvfrom instead of udp-listen in socat:
socat -u udp-recvfrom:3333,fork tcp:localhost:50000Then every UDP packet should trigger one TCP connection that is only brought up to send the content of the packet and then closed.
Test by doing:
echo play | socat -u - udp-sendto:localhost:3333(which sends a UDP packet whose payload contains the 5 bytes "play\n").
|
The UDP - must listen on port.
The TCP - must connect to a server.
I tried netcat and socat.
nc -v -u -l -p 3333 | nc -v 127.0.0.1 50000socat -v UDP-LISTEN:3333,fork TCP:localhost:50000Both work -- they delivered the message -- but the line is not ended.
VLC will only take the command if I close netcat/socat.
I monitored the connection with sockettest and the messages are one after another in the same line, like this:
playpausestopexitaddI need the line to be ended so that the message transmitted looks like this:
play
stop
exit
addMaybe the packet is not ended?
I am wondering if nc or socat have options to send the packet/end line after a certain amount of time.
If I add \n to the output as suggested by @roaima, I get play\nstop\nplay\n on a single line.
| Create UDP to TCP bridge with socat/netcat to relay control commands for vlc media-player |
One possibility that does not involve forking is to use the socat verbose output rather than the data. My version of socat -v includes the length of the data in the verbose output, so you know where it ends. For example,
mkfifo mypipe
while sleep 3
do printf "%sNONEWLINE" $RANDOM
done |
socat -u - UDP4:localhost:9999 &
socat -u -v UDP-RECV:9999 - >/dev/null 2>mypipe &
cat -uv mypipewill output before each data item (eg 9430NONEWLINE) a header starting > with the date and a length.
> 2018/07/28 10:29:33.965222 length=13 from=0 to=12
9430NONEWLINE> 2018/07/28 10:29:36.968335 length=14 from=13 to=26
26947NONEWLINE> 2018/07/28 10:29:39.971025 length=14 from=27 to=40
15126NONEWLINE |
I am using socat to intercept UDP messages and send them to a named pipe:
socat UDP-LISTEN:9999,fork PIPE:/tmp/mypipe,append
I am able to tail this pipe and see all the messages it receives.
I would like to pipe the output of tail -f /tmp/mypipe to sed to do some post-processing of the messages, but unfortunately some of them are not newline-terminated. This is a problem because it means multiple distinct UDP messages could be on the same line, and also because tail -f /tmp/mypipe | sed ... does not pass the last line if it is unterminated.
Ideally I would like to be able to add a custom message delimiter as they are sent to my pipe, so that I can easily find the message boundaries. If that's not possible then is there some way I can follow this file and pipe the final (potentially unterminated) line to another program for post-processing?
| How can I add message delimiters to a UDP stream socat is piping? |
(BTW, "virtual serial port" is a Windows term, on Unix these things are called "(pseudo) tty".)
What ctrl-alt-delor means is that you can just do one socat in the "serial device container", and one socat in the "code container" using the device; they communicate via a network connection, so one container has to know the IP address and port of the other container, and that's it (and you can choose which container connects to the other container). Also, the code running in the "code container" just uses the tty; so it doesn't depend on anything else except the path of the tty (which should be a parameter/commandline argument/etc., anyway).
Details of the socat call depend on some other details of what you want to do; maybe using tcp-listen and tcp is the simplest variant. Plenty of socat examples are e.g. here.
Edit
To explain the naming: A tty (teletype) is an abstraction over certain serial port parameters, together with a translation and interpretation of of characters (like end-of-line), and other things like the line discipline. A pseudo-tty is a tty without real hardware. A tty differs from a file in that it allows ioctls to set all these parameters.
So if your program has a feature to set, say, baud rate, you need a tty. If it doesn't, you could also use a named pipe.
However, it makes no difference if you use a named pipe or a tty with respect to sharing between containers: You'd still have to set up a common filesystem somewhere, where you can put either of them. And that's not necessarily how (docker) containers typically work.
OTOH, (docker) containers are usually ready for networking. So it might just be simpler to connect the containers via networking, instead of getting them to have a shared filesystems. And it has the additional advantage that the containers need not run on the same host (which docker containers don't assume). So it's a more natural fit.
You can do it any way you like, of course.
|
I can create two linked virtual serial ports on a Linux system with socat, and pretend one end is a serial device, and the other one is some code that uses the device. The socat command would look like:
socat -d -d pty,raw,echo=1 pty,raw,echo=0And it creates two ports on the system, e.g. /dev/pts/3 and /dev/pts/4.
Now, I want to go one step further, and have two docker containers representing the system: one container pretending to be the serial device, and the other container being the code using that device. The goal being that when in production, I can remove the virtual device container and just use the real sensor.
The problem is that I can't seem to find a way to share the devpts between two containers, and somehow it feels like it is not something good to do.
Would there be a way to achieve the exact same behavior (virtual serial ports) by using named pipes instead of pty? Then I could share the file (say "/home/user/folder/my_pipe") between the containers (actually I would mount "/home/user/folder" on both, and both would then access my_pipe).
Or is there another, better way to do all that with docker?
| Virtual serial port between docker containers |
You can certainly put an intervening socat in the way, and use its logging facilities. For example,
socat -v /dev/ttyUSB0,b19200,raw PTY,link=$HOME/myserial,raw,echo=0 2>logfile &
minicom -p $(readlink $HOME/myserial)This will log the data read in each direction, shown by ">" or "<":
< 2017/07/14 14:33:58.210584 length=3 from=0 to=2
hi
> 2017/07/14 14:33:58.214745 length=3 from=0 to=2
hi |
I am currently trying to log all communication from and to /dev/ttyUSB0 and simultaneously be able to connect minicom/screen to the same device for interaction.
I tried a couple of tools and tutorials but they all seem to occupy the device, so I can not connect to it with a terminal program.
Then I came across socat. It sounds promising, though it is able to redirect the /dev/ttyUSB0 to a PTS and log the transfered data to a file.
The idea is:
HW - /dev/ttyUSB0 <---> socat/logging <---> /dev/ptyX <---> minicom
Has anyone done this before?
Any help is appreciated.
Chris
| socat - UART logging and redirecting |
This command will do:
socat tcp-listen:5555,fork,reuseaddr \
'system:
PIPE=$(mktemp -u /tmp/pns_XXX)
mkfifo $PIPE
while read PIPE_MESSAGE<$PIPE; do
echo $PIPE_MESSAGE
done &
PID=$!
while read CLIENT_MESSAGE; do
for OTHER_PIPE in $(ls /tmp/pns_*); do
[ $PIPE != $OTHER_PIPE ] && echo $CLIENT_MESSAGE > $OTHER_PIPE
done
done
kill $PID
rm $PIPE'The idea is to create a named pipe for every new connection and then echoing to std output (i.e. send to client) whatever is read from the pipe. Std input (i.e. send by client to server) is read from and whatever is received is echoed to all the named pipes, except the own pipe.
|
ncat (from the nmap folk) has a neat default action of duplicating any input to all connected clients. E.g.:
Start a server on terminal 1:
% mkfifo messages
% exec 8<>messages # hold the fifo open
% ncat -l 5555 -k --send-only < messagesStart clients listening on terminals 2 & 3:
% nc localhost 5555Output something to the fifo on terminal 4 and watch the same message appear on all connected clients (terminals 2 & 3):
% printf 'Hello, clients.\n' > messagesIs this same pattern possible with socat?
Update: screenshot of Philippe's solution: | socat duplicate stdin to each connected client |
I don't fully understand why you need a virtual serial port at all. What happens if you just telnet 10.0.0.1 4030?
Next thing is to run socat without sudo as normal user and pick a path that's accessible, e.g. /tmp/vcom0 (or whatever).
If that doesn't work for some reason, and you obvious can do sudo, try changing owner
sudo chown your_username /dev/virtualcom0or permissions
sudo chmod o+rw /dev/virtualcom0Edit
Don't try to make udev rules for a particular pseudo tty. First, you don't know in advance which pseudo tty it is, second, pseudo tty's are used all over the place, and other programs will fail if they happen to create this pseudo tty for another user.
The cleanest solution is to use variant (1) (/tmp/vcom0).
If you insist on the other variants, make a short script that contains both the socat and the chmod/chown, and execute that script with sudo. You can follow symbol links with readlink, if necessary.
Another alternative is to write a short script that calls both socat as normal user, and stellarium with the link it made, and kills socat when it's done. Use that script to start stellarium.
|
Background: I want to use
this Wifi-to-Serial adapter
to control a telescope via
Stellarium
running on Kubuntu 16.04 (64 Bit).
I'd created a virtual com port using socat with this command line:
$ sudo socat pty,link=/dev/virtualcom0,raw tcp:10.0.0.1:4030and I see the new device here:
$ ls -l /dev/virtualcom0
lrwxrwxrwx 1 root root 10 2017-07-03 09:05 virtualcom0 -> /dev/pts/6
$ ls -l /dev/pts/6
crw--w---- 1 root tty 136, 6 2017-07-03 09:05 /dev/pts/6Trying to use /dev/virtualcom0 e.g. with picocomm works as long as I run picosomm with root privileges. But when I try to use the port with standard user privileges, I got an error:
$ picocom /dev/virtualcom0 --baud 9600 --imap lfcrlf
FATAL: cannot open /dev/virtualcom0: Permission deniedAny idea how to make the virtual com port accessable with standard user rights, maybe by defining a special udev rule for this?
Edit #1
Following the preferred approach of dirkt's answer, I'm now using:
$ socat pty,link=/tmp/virtualcom0,raw tcp:10.0.0.1:4030Note, that this also works fine on macOS (after installed socat via homebrew).
| How to use virtual serial port without root privileges? |
write either this on client side . notice the "raw" .
socat unix-connect:socket -,raw,echo=0
or this on server side . notice the "echo=0"
socat unix-listen:socket exec:"python",pty,echo=0
but not both . alternatively raw on client stdio with echo=0 on the server pty is fine , but echo=0 must not be applied twice .lets look at the two 1+1's . they are echos but with different meanings . the first echo is from line buffering of the client terminal , and the second is from the terminal on the server side created by socat .
>>> 1 + 1;
1 + 1;
2use of echo=0 alone on client stdio , socat informs its controlling terminal ( i.e. xterm or anything like ) to disable the echoing ( on-screen-display ) of stdio buffer , thus the first 1+1 disappears , and the second will show in the very place once return key is pressed . echo=0 on server pty prevents socat from echoing ( ping-pong ) the input it receives back to the client , thus the second 1+1 disappears . with raw on the client , buffering of stdio is disabled so every key don't wait till a return to be sent to the server , and server echos the key back immediatly . use raw on client stdio along with echo=0 on client stdio when a key is pressed it is first sent to the server then the server sends it back and is displayed on the client . use raw on client stdio along with echo=0 on server pty when a key is pressed it is displayed simultanously as it is sent to the server , but is never sent back .for commandline editing , sometimes it is sufficient to buffer a line on the client side and not send a whole line until we finish editing this line . however if powerful smart completion is desired , server side involvement is necessary .
|
If I run a normal interactive python session, input/output looks like this:
>>> 1 + 1;
2Now I'm trying to run it through socat, so I start a "server"
socat UNIX-LISTEN:$HOME/socket,fork EXEC:python,pty,stderrAnd connect to it from another terminal:
socat - UNIX-CONNECT:$HOME/socketWhich works almost fine except the input is echoed again too:
>>> 1 + 1;
1 + 1;
2How can I turn this off? echo=0 does not do what I want: this hides the input while I'm typing as well which is not very helpful. I want it to work just like a normal interactive session.
(using python and a local domain socket is just an example; the same occurs with other programs (e.g. cat, lua etc.) and other socket types, e.g. a TCP socket.
| socat disable double echo |
Question #1Q1: From the ss man page I can't find out, what does it mean e.g. * 8567674 without file path.From the docs it explains the Address:Port column like so:
excerptThe format and semantics of ADDRESS_PATTERN depends on address family.inet - ADDRESS_PATTERN consists of IP prefix, optionally followed by colon and port. If prefix or port part is absent or replaced with *, this means wildcard match.
inet6 - The same as inet, only prefix refers to an IPv6 address. Unlike inet colon becomes ambiguous, so that ss allows to use scheme, like used in URLs, where address is suppounded with [ ... ].
unix - ADDRESS_PATTERN is shell-style wildcard.
packet - format looks like inet, only interface index stays instead of port and link layer protocol id instead of address.
netlink - format looks like inet, only socket pid stays instead of port and netlink channel instead of address.PORT is syntactically ADDRESS_PATTERN with wildcard address part. Certainly, it is undefined for UNIX sockets.The last sentence is your answer.
Question #2Q2: Why there is no file path to unix socket for some cases?See this SO Q&A titled: How to use unix domain socket without creating a socket file.
excerptYou can create a unix domain socket with an "abstract socket address". Simply make the first character of the sun_path string in the sockaddr_un you pass to bind be '\0'. After this initial NUL, write a string to the remainder of sun_path and pad it out to UNIX_PATH_MAX with NULs (or anything else).
Sockets created this way will not have any filesystem entry, ....Question #3Q3: How can I sniff unix DGRAM socket through socat without having file path?Again more googling once you know what things are called: socat docs.
excerptABSTRACT-LISTEN:
ABSTRACT-SENDTO:
ABSTRACT-RECVFROM:
ABSTRACT-RECV:
ABSTRACT-CLIENT:
>
The ABSTRACT addresses are almost identical to the related UNIX addresses except that they do not address file system based sockets
but an alternate UNIX domain address space. To archive this the socket
address strings are prefixed with "\0" internally. This feature is
available (only?) on Linux. Option groups are the same as with the
related UNIX addresses, except that the ABSTRACT addresses are not
member of the NAMED group. |
From that article, I realized that:a UNIX domain socket is bound to a file path.So, I need to sniff DGRAM Unix socket through the socat as mentioned here. But when I try to retrieve the path for this purpose, I find that the target application uses a socket without file path.
The ss -apex command shows results both with and without file paths, e.g.:
u_dgr UNCONN 0 0 /var/lib/samba/private/msg.sock/32222 1345285 * 0 users:(("nmbd",pid=32222,fd=7))
u_dgr UNCONN 0 0 * 8567674 * 0 users:(("gnome-shell",pid=16368,fd=23))From the ss man page I can't find out, what does it mean e.g. * 8567674 without file path.
So, two questions:Why there is no file path to unix socket for some cases?
How can I sniff unix DGRAM socket through socat without having file path? | How can I sniff unix dgram socket without having file path? |
If you get stdio buffering apply the stdbuf command as a prefix to the actual command.
stty probably needs an explicit -echo.
For an alternative, if you don't need ssh encryption, look at the usbip module for making a usb device on one machine visible on another.
To avoid the tee logging, just use socat -v to get a copy of both data streams on stderr.
|
I'm currently using the following command. It reads from serial ttyUSB0 in local machine, and bidirectionally connects to ssh, through two tee commands for logging. On the remote end, socat connects stdio to the remote ttyUSB0:
stty -F /dev/ttyUSB0 raw 3000000ssh [emailprotected] stty -F /dev/ttyUSB0 raw 3000000socat /dev/ttyUSB0,raw,echo=0 SYSTEM:'"tee -a log_l2r | ssh [emailprotected] socat - /dev/ttyUSB0,raw,echo=0 | tee -a log_r2l"',pty,echo=0I want to make sure buffering does not spoil the realtime communication between two robot controllers. Line buffering is ok, but nothing more.
There is many connections in the above command and I'm unsure about potential buffered pipes/sockets. Could you help me spot them?
Also I need to remove any translation or echo (I believe stty ... raw ... already does this).
Is there some other preferred approach to solving this communication problem? i.e. other command?Running Debian GNU/Linux - Ubuntu
| Unbuffered socat command to connect serial ports in remote machines and log the data |
I'm not an expert on socat, but after a quick view to its name (SOcket CAT), it seems that it goes through opening two sockets and operating them in user-space.
As slm suggests, why do not configuring it via iptables?
Iptables is a user-space application which configures netfilter. Netfilter code is embedded in the kernel. It may result in a better performance, since forwarded packet does not need to be passed from kernel-space to user-space and vice versa.
Resourceshttps://www.systutorials.com/816/port-forwarding-using-iptables/
https://serverfault.com/questions/140622/how-can-i-port-forward-with-iptables |
I am using the command socat to port forward a connection from a real-time live stream.
TCP4-LISTEN:8080 TCP4:123.456.789.12:80The problem is it has added delay and low fps while the live stream without port forwarding works perfectly without delay and high fps. What might it be causing this?
Is there a way to fix this configuring socat or should I use another method? | Port Forwarding without delay and high fps in a real time live stream using socat |
OpenSSH of a sufficient version (OpenSSH 6.7/6.7p1 (2014-10-06) or higher) can do this, if the SSH is initiated from the client to the server system one could write something like
ssh -L /path/to/client.sock:/path/to/server.sock serverhostand then the client would connect to /path/to/client.sock and the server would listen at /path/to/server.sock. You probably will also need to set -o StreamLocalBindUnlink=yes, see ssh_config(5).
(And please don't use /tmp; improper use of /tmp can lead to local security exploits or denials of service or…)
|
I have two processes (Client and server) that communicate with each other using a Unix socket /tmp/tm.ipc. Both processes (Client and Server) don't support TCP.
Client -> /tmp/tm.ipc -> Server
Now, I want to separate both processes to run on two different machines that run in the same subnet. Therefore, I want to build sort of a TCP bridge in between.
Client -> /tmp/tm-machine1.ipc -> TCP port 15432 -> /tmp/tm-tm-machine2.ipc -> Server
I was thinking to use Socat, but this looks like that it only covers the server listening part.
socat -d -d TCP4-LISTEN:15432,fork UNIX-CONNECT:/tmp/tm.ipcNow I want to connect the client's Unix socket to that port. How can I do that?
| Building a Unix socket bridge via TCP |
You note that,the order of your arguments should not matter and I have often read the same on different sourcesInterestingly perhaps, the documentation for socat (man socat) disagrees:During the open phase, socat opens the first address and afterwards the second address. These steps are usually blocking; thus, especially for complex address types like socks, connection requests or authentication dialogs must be completed before the next step is started.And it's this that explains at least some of the behaviour you're seeing. Ideally, something should connect to the listening socket before an attempt is made to connect to the remote service. Otherwise, if you connect to the remote service before having a connection request on the local socket, you might get an idle timeout on the remote side.Local first, then remote:
socat -v tcp-listen:1433,bind=0.0.0.0,fork,reuseaddr tcp:localhost:11433 # YesRemote first, then local:
socat -v tcp:localhost:11433 tcp-listen:1433,bind=0.0.0.0,fork,reuseaddr # No |
The man page of socat states that socat is a command line based utility that establishes two bidirectional byte streams and transfers data between them. Based on that, the order of your arguments should not matter and I have often read the same on different sources.
But sometimes I have the feeling that order does indeed matter. For example: On a customers network I have an embedded system that I'm able to access via SSH. That embedded has direct access to a MS SQL database. When I want to debug some thing in the database, I'd like to use Azure Data Studio which runs on a VirtualBox VM on my host (with ip 192.168.100.1). So a simple ssh -L1433:dbserver:1433 won't help. That's where I use socat.
First I use local forward and connect the target port 1433 to my local port
11433 with
ssh my-remote-embedded -N -L11433:dbserver:1433then I use socat to create a direct connection between port 11433 and 1433
that is bound to 0.0.0.0 so that the port can be accessed in the virtual
machine.
If I do this:
socat -v tcp:localhost:11433 tcp-listen:1433,bind=0.0.0.0,fork,reuseaddrthen Azure Data Studio tries to connect to 192.168.100.1:1433 but the connection
sort of works, but not really. Azure Data Studio can indeed connect (thanks to
-v option I can see on the socat output that bytes are flowing in both
directions) and my connection icon turns green but it fails to fetch the list of
databases and regular queries also don't work.
However if I swap the order of the socat call to this:
socat -v tcp-listen:1433,bind=0.0.0.0,fork,reuseaddr tcp:localhost:11433then Azure Data Studio after a restart connects immediately and fetches the
list of databases without a problem, my queries work.
And if close Azure Data Studio and restart socat with swapped parameters, then
it happens again: the connection barely works.
So it seems that the arguments order for socat does really matter. Am I
crazy? What am I missing here?
I'm aware that at https://learn.microsoft.com/en-us/azure-data-studio/download-azure-data-studio?tabs=win-install%2Cwin-user-install%2Credhat-install%2Cwindows-uninstall%2Credhat-uninstall#install-azure-data-studio there is an installation guide for linux. My question is not about that, it's about socat and this is just an example where I can reproduce the behaviour every time.
| socat parameter order seems to matter |
You can tell socat to associate a pty with the awk program; this forces awk to run in line buffered mode and you get the immediate responses you're looking for.
Here's the command line to listen on port 9000:
socat TCP4-LISTEN:9000 SYSTEM:'/tmp/awk.sh',pty,echo=0And here's the contents of the script /tmp/awk.sh:
#!/usr/bin/awk -f
#
BEGIN { print "This is the awk socket" }
{ print NR, $0 }
END { print "All done" }Sample run:
$ nc -vvv otherhost 9000
otherhost [192.168.1.15] 9000 (?) open
This is the awk socket
hello world
1 hello world
how are you
2 how are you
boo
3 boo
^C sent 28, rcvd 61 |
I was playing around with awk, and I wanted to expose it over a tcp socket.
At first I tried, but failed with micro-inetd. Thinking that maybe the issue could be in the way that carriage returns/newlines characters are handled, I decided to try to switch to socat.
Using a remote command with socat is easy enough:
socat TCP4-LISTEN:9000 EXEC:/bin/cat
socat TCP4-LISTEN:9000 SYSTEM:"/bin/python -i"both of these work
But when trying the same with a simple awk command (for example `awk '{print NR}' to progressively count the number of lines received) I don't get anything back when connecting with socat from another shell on the same machine.
I tried plenty of things (some of these fail with a syntax error that is a bit obscure to me. I cannot even try to strace socat to see what exactly is being executed, since the actual command exec'ing is delegated to the shell):
socat TCP4-LISTEN:9000 SYSTEM:"/usr/bin/awk '{print NR}'"
socat TCP4-LISTEN:9000 SYSTEM:'/usr/bin/awk "{print NR}"'
socat TCP4-LISTEN:9000 SYSTEM:'/usr/bin/awk "{print\ NR}"'I also created a small script /tmp/testawk
#! /bin/sh
/usr/bin/awk '{print NR}'(also with an exec variant)
#! /bin/sh
exec /usr/bin/awk '{print NR}'Both of these work locally, but when invoking
socat TCP4-LISTEN:9000 EXEC:/tmp/testawkIt doesn't send me back the output
Thinking that the issue might be inheritance of the stdin/stdout handles and/or again handling of crlf... I tried also with:
socat TCP4-LISTEN:9000 EXEC:/tmp/testawk,nofork
socat TCP4-LISTEN:9000,crnl EXEC:/tmp/testawk
socat TCP4-LISTEN:9000 EXEC:/tmp/testawk,crnl
socat TCP4-LISTEN:9000,crnl EXEC:/tmp/testawk,crnlI've found someone else who complained about a similar issue, but apparently it failed to garner any attention
Any idea on what is going wrong?
| Expose awk over tcp (inetd, socat, etc.) |
I truly apologise. I found the answer to my question right after posting the question. The thing was that socat tried to open stdout for writing. I have edited the unit file like follows:
# /etc/systemd/system/dovecot-auth-bridge.service
[Unit]
Description=Dovecot auth bridge
After=dovecot.service
Requires=dovecot.service[Service]
Type=simple
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=dovecot-auth-bridgeExecStart=socat -d -d OPENSSL-LISTEN:9999,reuseaddr,fork,cert=/etc/ssl/certs/dovecotserver.pem,key=/etc/ssl/private/dovecotserver.key,bind=10.10.20.5,cafile=/etc/ssl/certs/eximserver.pem UNIX:/run/dovecot/auth-client
Restart=always[Install]
WantedBy=multi-user.targetNow the service starts inmediately. The output is written to the journal.
|
In order to use Exim's dovecot authentication, I need to bridge two unix sockets in two different machines: the exim server and the dovecot one.
To do so I'm using socat:
eximserver# socat UNIX-LISTEN:/run/exim4/auth-client,fork,group=Debian-exim,mode=660 OPENSSL:10.10.20.5:9999,cert=/etc/ssl/certs/eximserver.pem,key=/etc/ssl/private/eximserver.key,cafile=/etc/ssl/certs/dovecotserver.pem,commonname=dovecotserverdovecotserver# socat OPENSSL-LISTEN:9999,reuseaddr,fork,cert=/etc/ssl/certs/dovecotserver.pem,key=/etc/ssl/private/dovecotserver.key,bind=10.10.20.5,cafile=/etc/ssl/certs/eximserver.pem UNIX:/run/dovecot/auth-clientIt works like a charm. Exim connects to dovecot throught the local /run/exim4/auth-client unix socket, which is connected via TCP/IP through a crypted connection to the other end, where it's connected to /run/dovecot/auth-client socket unix.
Now, I'd like to run socat as a systemd service to run it automatically after dovecot starts, so I wrote this systemd unit:
# /etc/systemd/system/dovecot-auth-bridge.service
[Unit]
Description=Dovecot auth bridge
After=dovecot.service
Requires=dovecot.service[Service]
ExecStart=socat OPENSSL-LISTEN:9999,reuseaddr,fork,cert=/etc/ssl/certs/dovecotserver.pem,key=/etc/ssl/private/dovecotserver.key,bind=10.10.20.5,cafile=/etc/ssl/certs/eximserver.pem UNIX:/run/dovecot/auth-client
Type=forking[Install]
WantedBy=multi-user.targetHowever, I keep getting a timeout error whenever I try to start the service:
dovecotserver# systemctl start dovecot-auth-bridge.service
Job for dovecot-auth-bridge.service failed because a timeout was exceeded.
See "systemctl status dovecot-auth-bridge.service" and "journalctl -xe" for details.dovecotserver# # systemctl status dovecot-auth-bridge.service
● dovecot-auth-bridge.service - Dovecot auth bridge
Loaded: loaded (/etc/systemd/system/dovecot-auth-bridge.service; disabled; vendor preset: enabled)
Active: failed (Result: timeout) since Wed 2021-07-14 09:38:42 CEST; 28s ago
Process: 13251 ExecStart=/usr/bin/socat OPENSSL-LISTEN:9999,reuseaddr,fork,cert=/etc/ssl/certs/dovecotserver.pem,key=/etc/ssl/private/dovecotserver.key,bind=10.10.20.5,cafile=/etc/ssl/certs/eximserver.pem UNIX:/run/dovecot/auth-client (code=exited, status=143)Jul 14 09:37:12 Dovecotserver systemd[1]: Starting Dovecot auth bridge...
Jul 14 09:38:42 Dovecotserver systemd[1]: dovecot-auth-bridge.service: Start operation timed out. Terminating.
Jul 14 09:38:42 Dovecotserver systemd[1]: dovecot-auth-bridge.service: Control process exited, code=exited, status=143/n/a
Jul 14 09:38:42 Dovecotserver systemd[1]: dovecot-auth-bridge.service: Failed with result 'timeout'.
Jul 14 09:38:42 Dovecotserver systemd[1]: Failed to start Dovecot auth bridge.I feel there's a problem because socat doesn't go to background, but keeps running in foreground, so the service fails after a minute or so because of the timeout.
Maybe I should wrap the socat command in a shell script to run it in the background like this:
# /usr/local/bin/dovecot-auth-bridge.sh
#!/bin/bash
/usr/bin/socat OPENSSL-LISTEN:9999,reuseaddr,fork,cert=/etc/ssl/certs/dovecotserver.pem,key=/etc/ssl/private/dovecotserver.key,bind=10.10.20.5,cafile=/etc/ssl/certs/eximserver.pem UNIX:/run/dovecot/auth-client &Nonetheless, I wonder whether there's a better way to do it.
Regards,
| How to run socat as a systemd service to bridge two remote unix sockets? |
OP mentions ip-pktinfo which is usually a Linux socket option (for IP_PKTINFO). I'll assume Linux below (but see notes at the end for *BSD). This option is actually not needed (also see notes at the end), but could be added for additional information.The key part is to use the option reuseport which toggles the SO_REUSEPORT socket option:SO_REUSEPORT (since Linux 3.9)
Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket
(including the first socket) prior to calling bind(2) on the socket.
To prevent port hijacking, all of the processes binding to the same
address must have the same effective UID. This option can be employed
with both TCP and UDP sockets.Except for this missing option, OP already got all that was needed.
Mostly for other readers' benefit, I'll describe what's done and give a complete example.If one socat command can't do the work due to limitations, using two socat, splitting the full-duplex communication channel into two simplex channels, will for this case.
One will be used for reading back the answers, the other for sending the broadcast. Again, to workaround socat limitations, the reading socat has to use UDP-RECVFROM with fork and -u (for read-only, so its results are going to stdout, rather than being sent back to the responder) rather than the normally natural choice of UDP-RECV: that's to allow to fork one command per packet and transmit via environment variables the metadata for each packet. Also as OP wrote, a port has to be chosen in advance in order to have them both use the same. The sending socket too must use -u to avoid risking to read back the answer and stealing it to the other dedicated socat command.
Here's an example in a LAN with the local system having 192.0.2.2/24 and the peer system having 192.0.2.3/24.
peer system (responder) named peer:
$ socat udp4-recvfrom:30718,fork system:hostnamelocal system's term1 (could optionally also use ,ip-pktinfo):
$ socat -u udp4-recvfrom:30222,reuseport,fork system:'cat; printenv|grep -E \"SOCAT_.*(ADDR|PORT)\"'local system's term2:
$ echo dummyprobe | socat -u - udp-datagram:255.255.255.255:30718,bind=:30222,reuseport,broadcastresponse received on term1:
peer
SOCAT_PEERADDR=192.0.2.3
SOCAT_PEERPORT=30718NotesFreeBSD has a description similar for SO_REUSEPORT (or rather, Linux aligned lately to *BSD):SO_REUSEPORT allows completely duplicate bindings by multiple
processes if they all set SO_REUSEPORT before binding the port. This
option permits multiple instances of a program to each receive
UDP/IP multicast or broadcast datagrams destined for the bound port.ip-pktinfo is not needed to retrieve peer's address. It's needed to retrieve the local address and is mostly useful for a multi-homed system so it knows on which of its multiple addresses received a datagram, or else also to know if the received datagram was a broadcast. The peer's address information is always available even without this option. *BSD just requires to replace this option with ip-recvdstaddr,ip-recvif (=> IP_RECVDSTADDR + IP_RECVIF) to receive the same information. |
I'm trying to implement a simple proprietary discovery protocol using socat. The discovery is done by sending a UDP broadcast to a well-defined port with a small payload, then listening to "replies" from these devices on my network.
This works if I use bidirectional socat and "responses" go to stdout:
echo -ne "\x00\x01\x00\xF6" | socat -t5 - udp-datagram:255.255.255.255:30718,broadcast |xxd -pExample responses from a few devices on my local network (each line is a response from a different device):
000000f70020300258366d112c15000062a71b21ff0000000080a3d2ded9
000000f70020300258366d112c15000062a71b21ff0000000080a3a40670
000000f70020300258366d112c15000062a71b21ff0000000080a3b94ca0
000000f70020300258366d112c15000062a71b21ff0000000080a3a4046bThe payloads are what I expect, however what I'm missing is the sender metadata, specifically the sender's IP that I would get if I used ip-pktinfo,fork SYSTEM:. So what I want is to send the initial broadcast from stdin but use SYSTEM to handle the resulting packets coming back.
I've tried a few variations of -u unidirectional mode but I don't seem to receive data on my listener:
# Listener:
socat -u udp-recvfrom:30222,reuseaddr,ip-pktinfo,fork SYSTEM:./test.sh &# Broadcast:
echo -ne "\x00\x01\x00\xF6" | socat -u - udp-datagram:255.255.255.255:30222,sourceport=30222,broadcast,reuseaddrNote from "this end" the source port may be random so I'm explicitly choosing 30222 so my broadcast source port will match my response listener. e.g. if the broadcast comes from port 9987 clients will send their unicast response back to port 9987. If I run the unidirectional broadcast this way, I will occasionally get a response; I have a feeling it depends on how quickly the broadcast process quits.
(I intend to check packet captures next; I'm testing on a remote machine and I have to refresh my memory on tcpdump first.)
References:http://www.dest-unreach.org/socat/doc/socat-multicast.html
http://www.dest-unreach.org/socat/doc/socat.html#ADDRESS_UDP_DATAGRAM | Socat: send a UDP broadcast from stdin, but handling responses with SYSTEM |
If your command, as stated in the comments is:
socat -u FILE:somedatabase.raw TCP-LISTEN:4443,keepalive,tos=36you can, on the sending side, do a seek and start serving from there:
socat -u gopen:somedatabase.raw,seek=1024 TCP-LISTEN:4443,keepalive,tos=36on the receiving side you also need to seek:
socat tcp:example.com:4443 gopen:somedatabase.raw,seek=1024Check the manpage for socat, there are other options you might be interested in.
|
I have to transfer a 400Gb database consisting of a single file over the Internet from a server where I have full control to an other computer at the opposite border of the ocean (but which uses a slow connection). The transfer should take a full week and in order to reduce all protocol overhead (even using ftp would had 10Min overhead), I’m using a raw tcp connection.
I already transferred 10% of the file, but I learned there will be a scheduled outage in some hours.
How can I ask netcat or socat or curl to serve the FILE:database.raw at the offset it was interrupted? or
| How to resume a file transfer using netcat or socat or curl? |
You could simply add -v to socat and it will copy all i/o to stderr, prefixed by > or < to indicate the direction.
|
I'm interested in implementing the advanced content filter example for postfix.
socat tcp-listen:10026,reuseaddr,fork tcp:localhost:10025
This is a simple "passthru" that works, but obviously doesn't do any filtering or responding.
My goal is to have this socat command work exactly as it does (two-way forwarding between the two connections), but also one-way forward its input to a PHP script.
How would I do that?
Possible duplicate question (unanswered as of today)
For more background... I would like to avoid the limitations of the "simple" content filter via pipe but I don't want to implement a full SMTP client and server to handle the postfix <--> filter <--> postfix transaction.
I do not need to filter the mail, but I do need to track it. My thought is that I could forward the network traffic per usual, but have a PHP script that tracks the data passing over the wire.
| socat forward input to both tcp-connect and exec (script) |
This is a classic use of netcat. But this is unix.SE so my answer will be completely in unix.
Note: netcat has different names on different distros:netcat: alias to nc on some distros
nc: GNU netcat on linux or BSD netcat on *BSD
ncat: Nmap netcat, consistent on most systemsOptions between different versions of netcat vary, I'll point out where different version may behave differently. Moreover, I strongly recommend installing the nmap version of netcat (ncat) since its command line options are consistent across different systems.
I'll be using ncat as the netcat name thorough the answer.
TCP
To use TCP to control a machine through netcat you have two options: using a named pipe (which works with all versions of netcat) and using -e (which only exists in the linux version, or, more exactly, -e on *BSD does something completely different).
On the server side you need to perform either:
mkfifo pinkie
ncat -kl 0.0.0.0 4096 <pinkie | /bin/sh >pinkieWhere: 0.0.0.0 is the placeholder for "all interfaces", use a specific IP to limit it to a specific interface; -l is listen and -k keep open (to not terminate after a single connection).
Another option (on linux/ncat) is to use:
ncat -kl 0.0.0.0 4096 -e /bin/shTo achieve the same result.
On the client side you can use your app or simply perform:
ncat <server ip> 4096And you are in control of the shell on the server, and can send commands.
UDP
UDP is similar but has some limitations. You cannot use -k for the UDP protocol without -e, therefore you need to use the linux/ncat to achieve a reusable socket.
On the server side you do:
ncat -ukl 0.0.0.0 4096 -e /bin/shAnd on the client side (or from your app):
ncat -u <server ip> 4096And once again you have a working shell.
|
I want to config a PC with necat or socat to execute a script when I tell the server to do this.
I have an old app cappable to send simple message UDP prefered.
The message is stored in a playlist.example
Let's say I want to send a message to open a macro/script to the PC that is running netcat/socat
"C:\Users\xxx\Desktop\script.bat" the server needs to listen on a port.
and execute the program when the command its received
how I do this? I don't know how to start I found nothing on internet.
PS. please don't mind UDP security or reliability; it's a LAN thing, and I don't need the server to tell me anything back.
| Controling a PC via tcp/udp commands necat/socat |
The fork option tells socat to continue listening in the main process and handle connections in the child processes. This enables it to serve multiple minecraft server instances at once, one for each client that connects. It also means that the socat server will continue listening for new connections after all of them have disconnected, so that it can continue serving more minecraft server instances to clients that connect.
If you simply remove this fork option, it should only accept one connection and serve one minecraft server and then exit when the server stops.
|
I want to run the minecraft server.jar with an attached tcp socket, so I use:
socat EXEC:"java -jar server.jar nogui" TCP-LISTEN:25567,forkI can connect (and disconnect) to the server without any problems via telnet. But when I stop the server (via /stop) the server terminates (checked with ps auf, the process is definitely gone) but socat just doesn't terminate.
How can I start socat so it terminates after the EXEC-child is terminated? (I already tried using SYSTEM: instead of EXEC: but that was trying)
| How can I run socat so it terminate after child exits |
If possible, the easiest may be to adjust the software to emit hex. Most software will likely already have sdio.h (or equivalent) and hex-of-the-serial-data simply requires printf calls (or equivalent) on the data going to and from the serial file descriptor. No complication of an extra process ferrying the data to and fro and little extra latency.
If you're in a hurry something like strace (or sysdig SystemTap etc) could be used to record the communication though strace will slow a process down, a lot, and the output will require post-processing; the other two are kernel modules so may not be suitable.
strace -xx -y -e trace=read,write -p $pid_of_your_program_hereAt the hardware level a Bus Pirate or similar may be another way to tap into the communication.
Meanwhile, socat(1) does appear to have a handy -x for hex option:
-x Writes the transferred data not only to their target streams,
but also to stderr. The output format is hexadecimal, prefixed
with "> " or "< " indicating flow directions. Can be combined
with -v .which after some experimentation I was able to listen in on a random Arduino via:
socat -x PTY,link=/dev/blah,raw,wait-slave /dev/serial/by-id/usb-Arduino...and then your software could open up /dev/blah (or maybe instead run it via EXEC?). Note that no raw option was specified after the /dev/serial/by-id/usb-Arduino... path as with that set there were tcgetattr(6, ...): Inappropriate ioctl for device errors when socat tried to configure it. The socat output will likely also require post-processing, as it looks something like:
--
2017/10/09 16:32:20 socat[30806] I transferred 1 bytes from 6 to 5
< 2017/10/09 16:32:20.475916 length=31 from=2042 to=2072
52 65 71 75 65 73 74 69 6e 67 20 74 65 6d 70 65 Requesting tempe
72 61 74 75 72 65 73 2e 2e 2e 44 4f 4e 45 0a ratures...DONE.
-- |
I have been trying to get a HEX dump of what is being sent/received to CP2102 serial converter chip. I can find examples of people monitoring hardware serial ports /dev/TTYS0 and the like.
socat -d -d pty,link=/dev/ttyUSB0,raw,echo=0 pty,link=/dev/ttyUSB1,raw,echo=0Does anyone know of a resource that could tell me how to monitor a USB port like this? So far nothing has worked. Maybe I just don't understand the rerouting side of serial monitoring or something?
| socat - Monitoring USB port to standard CP2102 serial adaptor |
Your problem is that you have not specified you want unidirectional pipes. The socat man page explains how in this case PIPE: is like an echo.
What probably happened is that when you first wrote the date into the fifo 1, your socat read it, wrote it to fifo 2, then noticed there was input on fifo 2 so read it and wrote it to fifo 1, and so on busy looping until the first cat on fifo 2 managed to empty it before socat read it. Thereafter this first cat will continue reading the fifo, never seeing an end-of-file, and you can continue writing the date into the fifo.
You can see this if you add the -v option to socat to show the i/o.
Adding -u for unidirectional i/o makes it what you probably wanted, but now the socat will exit after the date is written and read, so you will need a loop for it:
while socat -v -u PIPE:/tmp/pipe1 PIPE:/tmp/pipe2; do echo new; done &With your tar version you could put the socat command inside the /tmp/chvol script instead.If you have a real tape drive, you might also look at a solution using nbd-server to export a block device over the network.
|
I'm trying to use socat on two systems in order to send a multivolume tar from one system to the other. Multivolume is an absolute requirement as I'm trying to shift potentially petabytes of data to a mounted tape archive.
Ultimately, I'm want to do something like this:
# on system1:
socat PIPE:/tmp/pipe1 SYSTEM:"ssh system2 socat - PIPE\:/tmp/pipe2" &
tar -M -L 10G -F /tmp/chvol -cvf /tmp/pipe1 <source-path> &# on system2:
cat /tmp/pipe2 > file001.tar
cat /tmp/pipe2 > file002.tar
...(The chvol script just echos the path /tmp/pipe1.)
As I've not been able to get this working yet, I'm running the following much-simplified test on one single system:
socat PIPE:/tmp/pipe1 PIPE:/tmp/pipe2 &
sh -c 'while sleep 1; do echo "sending date ..."; date > /tmp/pipe1; done' &
sh -c 'while sleep 1; do echo "slurping ..."; cat < /tmp/pipe2; done' &which is meant to simulate a writer process repeatedly opening, writing, closing and a reader process repeatedly opening, reading until EOF, closing.
But this doesn't behave as I expected: the writer is seemingly happy, but the reader reads all the accumulated text in one go and thereafter remains blocked in a cat < ... call.
Can anybody explain (1) what is actually happening in the much-simplified test and (2) what I should be doing instead?
I have tried various shut-* options on both pipes (on the assumption that the problem is in the propogation of EOF) and done a lot of googling.
| socat pipe to pipe for multiple open-write-close and open-read-close operations |
The only hack I can think of, would be to make a directory with fake "binaries" using the same names as the list you provide, symlinked to some inert executable script like:
#!/bin/sh
echo "This is a fake binary, and should never execute. Please check your path."
exit 0Then make sure your PATH is pointing to this directory as the last one. Now hitting TAB should make your shell interpreter think you're looking for another file or binary.
|
Is this possible to provide a customized 'complete' function to the readline library that goes inside socat? I mean something quicker than recompiling the readline, some hook or text file configuration?
socat readline EXEC:applicationIn the example above, I want to be able to do tab completion of a set of predefined commands.
| How to provide a customized function 'complete' to readline of socat |
$ ncat -4 -vv --exec cat -l -p 5555nmap's ncat requires a full path for its --exec parameter. Use /bin/cat instead of cat.I try to use -vv & -lf in the socat command to get more information about the tcp6 traffic but no significant log was written to the log file.To get verbose socat output, specify the -d switch a few times.
Other than the above issues, I managed to successfully reproduce your setup, and it seems to work as you've intended. Check the debug output to narrow down your problem.
|
I'm using socat to route incoming tcp6 to tcp4. The destination (tcp4) is a pod/container with the pod service external-ip. Within the container I use ncat to listen for the port 5555.
# socat TCP6-LISTEN:5555,reuseaddr,fork,bind=[fe80::250:56ff:fe91:bd5c%ens192] TCP4:10.40.5.125:5555 (Update)socat return Connection refused (Update)
2018/07/27 01:15:41 socat[26914] E connect(5, AF=2 10.40.5.125:5555, 16): Connection refusedI'm getting no acknowledgment from within the container (# ncat -4 -vv --exec cat -l -p 5555)
I try to use -vv & -lf in the socat command to get more information about the tcp6 traffic but no significant log was written to the log file.
Before attempting tcp6 format I was able to route tcp4 traffic to tcp4 same destination listed above using socat. The command is below,
# socat TCP-LISTEN:5555,fork TCP:10.101.74.206:5555Can someone please point what I am missing for tcp6?
OS: CentOS 7.5
| socat route tcp6 traffic to tcp4 |
I took both of your advice and tried doing it some other way. In the end I decided to do it as a web page as I could then add additional functionality beyond volume and on/off. I relied heavily on lots of bits and pieces cobbled together from several sources so thanks to all of them. I used node.js with sockets.io and after a bit of trial and error got something that works, with feedback from the device (so it can initialize its state when the page loads) and which doesn't incrementally duplicate nested replies (that took some figuring out as I knew nothing about node or sockets up until a few days ago!) Here it is. Probably not very pretty to anyone who knows this stuff properly, but it appears to do what I want! To use it, install node and run the node.js file using the command: nodejs main.js Put the index.html and style.css files in a sub directory (relative to the folder with node.js) called "public" (without the quotes). Then point your browser at the host (running main.js) with the port number appended to the url ( :8080 in this case).
By the way, this is for an Onkyo TX-SR804 but should work for their other RS-232 controlled receivers too, using an RS-232 to USB adaptor (a few bucks off amazon).
This is the node.js file:
var express = require('express');
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyUSB0", {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1
}
);server.listen(8080);
app.use(express.static('public'));
var paramVal = 0;
var countRep = 0;
var countSend = 0;
var buf = new Buffer(16);
var global_socket;io.sockets.on('connection', function (socket) {
global_socket = socket;
global_socket.on('toOnkyo', function (data) {
paramVal = data.value;
buf.write(paramVal, "utf-8");
serialPort.write(buf);
console.log(paramVal.toString().substr(0,7) + " (" + parseInt(paramVal.toString().substr(5,2),16) + ")\r\n");
global_socket.emit('toOnkyo', {value: paramVal});
console.log('new'+paramVal);
countSend=countSend+1;
console.log('count send '+ countSend);
}
);
}
);
serialPort.on('data', function(data) {
console.log('data received: ' + data.toString().substr(0,7) + " (" + parseInt(data.toString().substr(5,2),16) + ")");
global_socket.emit('onkyoReply', {value: data.toString().substr(0,7)});
countRep=countRep+1;
console.log('count '+ countRep);
}
);
console.log("running");This is the HTML index.html file that you point your browser at. It should be in a folder called public, a sub folder of the one with node.js in it. when you point your browser at the server running node.js, include the port number (8080 in this case)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Onkyo Controller</title>
<meta name="viewport" content="width=400px" />
<script src="socket.io/socket.io.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!--
Sent: <span id="sliderVolText"></span><br>
Reply: <span id="replyTextHex"></span>
(Decimal: <span id="replyText10"></span>)<br>
Mode: <span id="modeText"></span><br>
PowerText: <span id="powerText"></span><br>
Power: <span id="power"></span><br>
onoffText: <span id="onoffText"></span><br>
onoff: <span id="onoff"></span>
--><span id="sliderVolText" style="display:none"></span>
<span id="replyTextHex" style="display:none"></span>
<span id="replyText10" style="display:none"></span>
<span id="modeText" style="display:none"></span>
<span id="sourceText" style="display:none"></span>
<span id="powerText" style="display:none"></span>
<span id="power" style="display:none"></span>
<span id="onoffText" style="display:none"></span>
<span id="onoff" style="display:none"></span> <script>
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
</script> <form class="onoffswitch" >
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" onclick="showOnoff(checked)">
<label class="onoffswitch-label" for="myonoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</form>
<!--
<form name="powerForm" method="get" action="" onsubmit="return false;">
<p> <label for="power0"><input type="radio" value="0x00" name="powerForm" id="power0" onclick="showPower(this.value)"> Off</label>
<label for="power1"><input type="radio" value="0x01" name="powerForm" id="power1" onclick="showPower(this.value)"> On</label>
</form>
-->
<form name="modeForm" method="get" action="" onsubmit="return false;">
<p> <label for="mode0"><input type="radio" value="0x00" name="modeForm" id="mode0" onclick="showMode(this.value)"> Stereo</label>
<label for="mode1"><input type="radio" value="0x01" name="modeForm" id="mode1" onclick="showMode(this.value)"> Direct</label>
<label for="mode2"><input type="radio" value="0x0C" name="modeForm" id="mode2" onclick="showMode(this.value)"> All Ch stereo</label>
<label for="mode3"><input type="radio" value="0x42" name="modeForm" id="mode3" onclick="showMode(this.value)"> THX Cinema</label>
<label for="mode4"><input type="radio" value="0x84" name="modeForm" id="mode4" onclick="showMode(this.value)"> PLllx THX Cinema</label>
<label for="mode5"><input type="radio" value="0x11" name="modeForm" id="mode5" onclick="showMode(this.value)"> Pure</label>
</form>
<br><form name="sourceForm" method="get" action="" onsubmit="return false;">
<p> <label for="source0"><input type="radio" value="0x00" name="sourceForm" id="source0" onclick="showSource(this.value)"> Computer</label>
<label for="source2"><input type="radio" value="0x24" name="sourceForm" id="source2" onclick="showSource(this.value)"> FM radio</label>
<!--
<label for="source1"><input type="radio" value="0x01" name="sourceForm" id="source1" onclick="showSource(this.value)"> Video 2</label>
<label for="source3"><input type="radio" value="0x26" name="sourceForm" id="source3" onclick="showSource(this.value)"> Tuner</label>
-->
</form>
<br> <form name="slideForm" method="get" action="" onsubmit="return false;">
<input type="range" id= "inputSlider" min="0" max="100" value="vol" step="1" oninput="showVolume(this.value)" />
</form>
<br>
<div class="results"></div>
<script type="text/javascript">
// function toggle(checked) {
// var elm = document.getElementById('checkbox');
// if (checked != elm.checked) {
// elm.click();
// }
// } var socket = io.connect();
var ctrlType = "";
socket.on('toOnkyo', function (data) {
ctrlType = data.value.toString().substr(2,3);
if (ctrlType == "MVL" && !(data.value.toString().substr(5,4)=="QSTN")){
document.getElementById("inputSlider").value = parseInt(data.value.toString().substr(5,2),16);
document.getElementById("sliderVolText").innerHTML = data.value;
}
if (ctrlType == "LMD" && !(data.value.toString().substr(5,4)=="QSTN")){
document.getElementById("mode").value = parseInt(data.value.toString().substr(5,2),16);
document.getElementById("modeText").innerHTML = data.value;
}
if (ctrlType == "PWR" && !(data.value.toString().substr(5,4)=="QSTN") ){
document.getElementById("power").value = parseInt(data.value.toString().substr(5,2),16);
document.getElementById("powerText").innerHTML = data.value;
}
if (ctrlType == "PWR" && !(data.value.toString().substr(5,4)=="QSTN") ){
document.getElementById("onoff").value = parseInt(data.value.toString().substr(5,2),16);
document.getElementById("onoffText").innerHTML = data.value;
}
if (ctrlType == "SLI" && !(data.value.toString().substr(5,4)=="QSTN")){
document.getElementById("source").value = parseInt(data.value.toString().substr(5,2),16);
document.getElementById("sourceText").innerHTML = data.value;
}
});
socket.on('onkyoReply', function (data) {
var done = false;
ctrlType = data.value.toString().substr(2,3);
document.getElementById("replyTextHex").innerHTML = data.value;
document.getElementById("replyText10").innerHTML = parseInt(data.value.toString().substr(5,2),16);
if (ctrlType == "LMD"){
setCheckedValue(document.forms['modeForm'].elements['modeForm'],"0x"+data.value.toString().substr(5,2));
}
if (ctrlType == "SLI"){
setCheckedValue(document.forms['sourceForm'].elements['sourceForm'],"0x"+data.value.toString().substr(5,2));
}
if (ctrlType == "PWR"){
var val = parseInt(data.value.toString().substr(5,2),16);
// setCheckedValue(document.forms['powerForm'].elements['powerForm'],"0x"+data.value.toString().substr(5,2));
document.getElementById("myonoffswitch").checked = (data.value.toString().substr(6,1) != 0);// console.log(ctrlType);
// If (val == 1) {
// document.getElementById("myonoffswitch").checked = true;
// }
// If (data.value.toString().substr(6,1)=='0') {
// document.getElementById("myonoffswitch").checked = false;
// } else {
// document.getElementById("myonoffswitch").checked = true;
// };
// document.getElementById('myonoffswitch').click();
}
if (ctrlType == "MVL" && done == false){
document.getElementById("inputSlider").value = parseInt(data.value.toString().substr(5,2),16);
document.querySelector('.results').innerHTML = parseInt(data.value.toString().substr(5,2),16);
done = true;
}
}); function showVolume(newValue) {
document.getElementById("sliderVolText").innerHTML="\!1MVL"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n";
socket.emit('toOnkyo', { value: "\!1MVL"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n" });
} function showMode(newValue) {
document.getElementById("modeText").innerHTML="\!1LMD"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n";
socket.emit('toOnkyo', { value: "\!1LMD"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n" });
} function showSource(newValue) {
document.getElementById("sourceText").innerHTML="\!1SLI"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n";
socket.emit('toOnkyo', { value: "\!1SLI"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n" });
}// function showPower(newValue) {
// document.getElementById("powerText").innerHTML="\!1PWR"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n";
// socket.emit('toOnkyo', { value: "\!1PWR"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n" });
// } function showOnoff(newValue) {
document.getElementById("onoffText").innerHTML="\!1PWR"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n";
socket.emit('toOnkyo', { value: "\!1PWR"+("0" + Number(newValue).toString(16)).slice(-2)+"\r\n" });
} socket.emit('toOnkyo', { value: "\!1LMDQSTN"+"\r\n" });
socket.emit('toOnkyo', { value: "\!1MVLQSTN"+"\r\n" });
socket.emit('toOnkyo', { value: "\!1PWRQSTN"+"\r\n" });
socket.emit('toOnkyo', { value: "\!1SLIQSTN"+"\r\n" }); </script>
</body>
</html>Finally the style.css file. Should be placed in the same folder as the index.html file.
body {
text-align: center;
margin-top: 50px;
background: #50D0A0;
}input[type=range]{
-webkit-appearance: none;
width: 80%;
}input[type=range]::-webkit-slider-runnable-track {
height: 10px;
background: #ddd;
border: none;
border-radius: 3px;
}input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: none;
height: 32px;
width: 32px;
border-radius: 50%;
background: /* goldenrod */ #34A7C1;
margin-top: -12px;
}input[type=range]:focus {
outline: none;
}input[type=range]:focus::-webkit-slider-runnable-track {
background: #ccc;
}
.radioLeft
{
text-align:left;
}.onoffswitch {
position: relative; width: 90px;
-webkit-user-select:none; -moz-user-select:none; -ms-user-select: none; left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%) }
.onoffswitch-checkbox {
display: none;
}
.onoffswitch-label {
display: block; overflow: hidden; cursor: pointer;
border: 2px solid #999999; border-radius: 20px;
}
.onoffswitch-inner {
display: block; width: 200%; margin-left: -100%;
transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px;
font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
box-sizing: border-box;
}
.onoffswitch-inner:before {
content: "ON";
padding-left: 10px;
background-color: #34A7C1; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: "OFF";
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}
.onoffswitch-switch {
display: block; width: 18px; margin: 6px;
background: #FFFFFF;
position: absolute; top: 0; bottom: 0;
right: 56px;
border: 2px solid #999999; border-radius: 20px;
transition: all 0.3s ease-in 0s;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
right: 0px;
} |
I would like to set up a service on a linux box that acts as a bridge between my old RS-232 controlled Onkyo receiver and my local network.
So far I can talk one way to it using socat:
sudo socat tcp-l:60128,reuseaddr,fork file:/dev/ttyUSB0,nonblock,raw,echo=0,crnl,waitlock=/ttyUSB0.lock &That lets me change settings like volume, source etc., but the reply that comes back to acknowledge the change is missing a simple string that newer ethernet equipped receivers include in their reply. As a result I can't use this to control the receiver using current phone apps that expect the response that the ethernet enabled units provide.
Is there a way to get socat to include the additional string as part of the response or can I get two instances of socat either side of some code which decides when and where to add extra strings to the message?
The Onkyo protocol for both the older RS-232 and the newer IP methods are described in this excel sheet if that helps:
http://blog.siewert.net/files/ISCP%20AV%20Receiver%20v124-1.xls
The auto-detect request "!xECNQSTN" that all the various modern onkyo controlling apps send, expects to get a reply like:
'!1ECNTX-NR609/60128/DX'
And that request happens after every state change like volume up, volume down, etc, so it looks like I need to do something like having two instances of socat running with some logic in between.
I could always just get a new modern receiver but this would be way more satisfying :o)
Any ideas how to do this are very welcome!
| Control an rs-232 receiver as though it understood more recent IP protocol |
This is the default, if I understand your question. The first socket is opened and blocks in listen. Only when a connection is made will the second-named connection be attempted. You can test this. E.g. listen on port 60127 and connect to port 60128 in one shell:
$ socat tcp-l:60127,reuseaddr tcp:localhost:60128It will block waiting. In another shell try to connect:
$ telnet localhost 60127
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.It fails, and the original command fails too:
socat[30293] E connect(3, AF=2 127.0.0.1:60128, 16): Connection refusedIf, however, you repeat the first socat, then add another on port 60128 with:
$ socat tcp-l:60128,reuseaddr -then the telnet will work. So, clearly the first socat does not try the second-named connection until needed.
|
I want to run socat as a server - against a target that will go up and down intermittently (cloud microservice environment).
I want socat to listen - and open the port when it gets a listener connection. (A socat server)
My question is: Is there a way to make socat not open the target connection until it receives a listener connection?
| Is there a way to make socat not open the target connection until it receives a listener connection? |
Just do:
#! /bin/sh -
{
printf '%s\n' "${1-default-id}"
awk '/abc/ && /def/ && ! /ghi/'
} | socat - tcp:n.n.n.n:7777${1-default-id} expands to the first positional parameter if specified or default-id otherwise. Replace with ${1?} to exit with an error if not passed any argument instead (or ${1?The error message} to specify an error message instead of the default).
We redirect the output of a command group that runs printf to output the ID and the filtering commands (here with your grep pipeline replaced with a single awk invocation that does the same thing a bit less clumsily) to socat/netcat.
Or to only print the ID if and when one line has been read and matches:
#! /bin/sh -
ID=${1-default-id} awk '
/abc/ && /def/ && ! /ghi/ {
if (!already_printed++) print ENVIRON["ID"]
print
}' | socat - tcp:n.n.n.n:7777Or to prepend the ID (and a space character) to every line:
#! /bin/sh -
ID=${1-default-id} awk '
/abc/ && /def/ && ! /ghi/ {
print ENVIRON["ID"], $0
}' | socat - tcp:n.n.n.n:7777Beware awk, like grep will buffer their output when it goes to a pipe (to anything other than a tty device). With the GNU implementation of awk (aka gawk), you can add a call to fflush() after each print to force the flushing of that buffer. See also the -Winteractive of mawk. In most awk implementations, doing a system("") would also force a flush. The GNU implementation of grep has a --line-buffered option to force a flush after each line of output.
Also note that tail -f logfile is short for tail -n 10 -f logfile. Chances are you actually want either tail -n +1 -f logfile for the whole log file to be processed, and then tail carrying on following the file, or tail -n 0 -f logfile to process only the lines being added from now on.
|
I am working on a process to send data via a pipe from one server to another for processing.
Although this is not the exact command, it might look something like this:
tail -f logfile | grep "abc" | grep "def" | grep -v "ghi" | netcat -q 0 n.n.n.n 7777I would like to wrap all those greps into a script and more importantly prepend the pipe to netcat with an identifier, so the command would look like this:
tail -f logfile | myscript.sh {id}The script listening on the other end should receive:
{id}
[Line 1 of the logfile]
[Line 2 of the logfile]
...Wrapping it in a script is easy:
#!/bin/sh
id=$1
grep "abc" | grep "def" | grep -v "ghi" | netcat -q 0 n.n.n.n 7777but I cannot figure out how to inject $id at the start.
The receiving end is using
socat -u tcp-l:7777,fork system:/dev/receivePipeso if there is a different way I could get the id (for example somehow as a parameter to /dev/receivePipe), or via an environment variable, that would work too.
EDIT: The final answer was figured out in the comments of the accepted answer:
#!/bin/sh
{
printf '%s\n' $1
grep "abc" | grep "def" | grep -v "ghi"
} | netcat -q 0 192.168.56.105 7777 | How do I inject a header line into a pipe via a shell script? |
socat /dev/null,ignoreeof tcp-listen:2003,fork,reuseaddr |
I'm trying to implement a TCP listener that accepts connections and then simply drops all of its input (it's for a test harness).
Right now, I'm using socat - tcp-listen:2003,fork,reuseaddr, but that prints the input to stdout. I don't want that.
I can't redirect the output to /dev/null, because I'm doing this in the alpine/socat docker container, and it's not actually using a shell, so redirection doesn't work.
If I try to use socat /dev/null tcp-listen:2003,fork,reuseaddr, then any connection is dropped immediately, presumably because socat can't read from /dev/null.
What's the best way to implement a TCP listener that simply drops everything on the floor?
| TCP listener that drops all of its input? |
In C, printf is part of the buffered I/O library – data written to the stream is "buffered" in memory (i.e., not written directly the the kernel).
By default, stdout (the stream to which printf writes data) is a line-buffered stream, which means that bytes are stored in the in-memory buffer until a newline is written to the stream (or some other even that triggers flushing happens).
If standard output isn't associated with a terminal, then stdout is a block-buffered stream, which means that bytes are stored in the in-memory buffer until the buffer gets full.
When you run your program at the terminal, the '\n' in your call to printf triggers the flush (since it's line-buffered):
$ ./a.out
Input
whatever-you-type
$If you redirect output to a file, you'll see a different behavior:
Terminal 1 Terminal 2
-------------------- --------------------
$ ./a.out > /tmp/out
$ cat /tmp/out
$
type-input
$
$ cat /tmp/out
Input
$ When you run socat without pts, the output stream is in block-buffered mode; when you run it with pts the output stream is in line-buffered mode.
If you want to override that behavior, you have a couple of options. You can call a function to explicitly cause any buffered data to be flushed:
printf("Input\n");
fflush(stdout);Alternatively, you can explicitly set the buffering mode of the output stream before calling printf:
setvbuf(stdout, NULL, _IONBF, 0); // _IONBF = Unbuffered
printf("Input\n");See Chapter 3 of Robert Love's book Linux System Programming for a more detailed explanation.
|
I have a small program that first outputs a string to the user and then takes an input. I instead want the program to work by sending and receiving from a port. To try to realize this I ran the command socat TCP4-LISTEN:1337,reuseaddr,fork EXEC:./program. From this command, I wanted to be able to run nc 127.0.0.1 1337 and expected the program to:Recieve the message from the program
Be able to provide input
Lost connetionHowever, when running the program using socat it goes like thisGive input
Message received from the program
Give another input
Lost connectionI don't understand why this happens. Is there any fault on my part using the socat command? And if it is, please tell me what is missing/wrong.
Here is the program.
#include <stdio.h>void vuln(void) {
printf("Input\n");
char buffer[256];
gets(buffer); // potential buffer overflow
}int main(void) {
vuln();
return 0;
} | socat: EXEC does not relay correctly |
Your main problem is probably that base64 -d (GNU base64 for me) buffers its output, and by the look of it, can't be told not to. Same goes for openssl base64 -d from my tests. GNU recode can be told not to buffer with GNU stdbuf though.
So with socat 2, you should be able to do something like:
socat tcp-listen:8080,fork,reuseaddr \
'exec1:stdbuf -o0 recode /b64 % nop | tcp:localhost:80'With socat 1, you could do:
socat tcp-listen:8080,fork,reuseaddr \
'system:"stdbuf -o0 recode /b64 | socat - tcp:localhost:80"'Which is essentially the same as yours but with the intermediate script inlined (and the non-buffering base64 decoding).
|
The goal: bidirectional communication while decode in a unidirectional way the incoming data
Theory: suppose to have a proxy/ server that listens on port 8080 which needs to handle multiple clients at once. The data coming in is base64 encoded, it should be decoded and forwarded to another port ( 80 ).
Practice: I would like to use socat because of all its features ( and also because it is the only one I know that can do all these things, if you know something else could be fine too ):tcp to tcp
udp to tcp
fork and reuseaddr
exec commandsI'm looking for something like that:
socat tcp-listen:8080,reuseaddr,fork exec:/path/to/myscript.shwith /path/to/myscript.sh:
#!/bin/sh
exec base64 -d | socat - tcp:localhost:80But this sadly does not fit my case because is not completely bidirectional
| How to use socat to implement a base64 decoding proxy? |
We did some test streaming videos via socat for a day or two and so far performance and system impact seems good.
First feedback from customers also.
You have to make sure that you don't use socats fork and don't log extensively because that will have noticeable negative impact on your system.
I suggest to use socats UDP-RECV for incoming traffic and UDP-DATAGRAM for outgoing traffic.
This combination proved to be the must performant and stable solution.
Other wouldn't work are have a negative impact on the system.
Be sure to read socats documentation it will explain how the different options work.
|
We have a server which main focus is to stream data from one point to another.
e.g.
transfer data form 192.168.0.10:5000 to 192.168.0.20:6000
transfer data form 232.0.0.1:5000 to 192.168.0.20:6000
transfer data form 192.168.0.255:5000 to 192.168.0.20:6000I assume the best way to do that would by iptables but since we need to support multicast this doesn't seem to be an option (at least for multicast)
I know how I can make socat run as a service but my question is if I should run socat as a service.
Sometimes there might be hours where it would idle and days where it would transfer data every second.
Is socat ready to run 24/7 and receiving/transmitting data?
| use socat as a service 24/7 |
Assuming the answer is one newline-delimited line of text, with bash, you could always do:
IFS= read -r answer < <(
echo 'sign 00:07:32:46:04:75' |
socat -t 5 - UDP4-DATAGRAM:239.192.0.2:9000)That would return as soon as there's an answer and socat would be left running in background for the remaining time.
In zsh, you'd need to add a & at the end of the echo|socat pipeline for it not to wait for it. You may actually want to add it for bash as well to be future-proof in case bash decides to change the behaviour in the future.
If the answer can be more than one line or is not newline delimited, with zsh you could do:
zmodload zsh/system
(echo 'sign 00:07:32:46:04:75' |
socat -t 5 - UDP4-DATAGRAM:239.192.0.2:9000 &) | sysread answerThe sysread builtin does one read() system call of size 8192. That assumes socat writes the answer on the pipe in one write() system call (which it does).
Portably, you could always resort to dd for that:
answer=$(
(echo 'sign 00:07:32:46:04:75' |
socat -t 5 - UDP4-DATAGRAM:239.192.0.2:9000 &) |
dd bs=8192 count=1 2> /dev/null
)(note that command substitution strips all trailing newline characters).
If you wanted to avoid socat hanging around for those few extra seconds after that, you could do something like:
answer=$(
(echo 'sign 00:07:32:46:04:75' |
sh -c 'echo "$$"
exec socat -t 5 - UDP4-DATAGRAM:239.192.0.2:9000 &
) | {
IFS= read pid
dd bs=8192 count=1 2> /dev/null
kill -s PIPE "$pid"
}
) |
I use this in a script
echo $(echo "sign 00:07:32:46:04:75" | socat UDP4-DATAGRAM:239.192.0.2:9000 -)but this does immediately stop and I get no answer from the server
if I do
echo $(echo "sign 00:07:32:46:04:75" | socat -t5 UDP4-DATAGRAM:239.192.0.2:9000 -)it always waits the 5 seconds also when the repsonse would be available after 1 second.
Is there a way to stop the command immediatley after I received the first message?
| socat wait for answer |
But any connection from Windows to WSL2 just worksAs background, it's important to understand that the WSL2 network is NAT'd behind a virtual, Hyper-V switch. It really is a separate layer 2 network from the Windows host.
Communication from Windows to WSL2 is considered outbound traffic from Windows, and inbound to WSL2, so no firewall rules are needed. By default, Windows allows most outbound traffic, and your Linux distribution running under WSL2 accepts most inbound traffic.
We can use that to our advantage in this case ...Is it possible to run a client/server pair as an intermediary service, to mirror any service on the WSL and make it accessible from the WSL?You have this tagged socat and that's a reasonable idea. I've used socat before in a similar way successfully, but (a) it's been a while, (b) I'd need to reproduce the recipe I used and tweak it to the X server, and (c) socat's options are kind of a pain to work through. It's powerful, but not necessarily easy to use.
So let me propose a built-in, much easier alternative -- ssh from Windows to WSL2 with X forwarding. It's really designed to do just this type of traversal.Enable the OpenSSH client for Windows (see [doc] (https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse?tabs=gui#install-openssh-for-windows). No need for the server in this case, since you'd have to open a firewall rule for that (which you've said you can't). It's already installed with Windows, you just need to enable the feature.Enable the SSH server in your Linux distribution under WSL2. You don't mention which distribution you are running, but under Ubuntu (the default distribution), you need to (if I recall correctly):Edit the sshd config: sudo -e /etc/ssh/sshd_config and choose a different port -- Let's say 2222.
Optionally enable PasswordAuthentication if you won't be using a key.
Ensure that X11Forwarding=yes, which it already should in Ubuntu.
Save and exit.
sudo service ssh start
If you get a message about host keys missing, try sudo dpkg-reconfigure openssh-server and then restart the service.From Windows, start XLaunch (VcXsrv) with the default options + "Disable access control".From PowerShell:
$env:DISPLAY="localhost:0"
ssh -Y -p 2222 wslusername@localhostNote: See this SU answer for why the localhost is critical in this case.You should be logged into the WSL2 instance, with X forwarding in place. xterm, etc. should launch into VcXsrv. |
Problem
Can't connect to Windows X Server (VcXsrv) from WSL2 due firewall rules (sometimes it works, but sometimes it doesnt; it's very strange). Changing the firewall rules is not possible.
But any connection from Windows to WSL2 just works.
Idea
Is it possible to run a client/server pair as an intermediary service, to mirror any service on the WSL and make it accessible from the WSL?
------------Windows Host------------
| [Windows X Server] <--- [Client] |
-----------------------------↑------
|
----------------WSL----------v---------
| [XGui Client] ---> [Mirror service] |
--------------------------------------- | Connect to host machine from WSL2 |
Okay, so it turns out it is not so trivial.
User input when
$ wgsh
wgsh@vultr /$and piped commands:
$ wgsh <<EOD
echo 1
echo 2
echo 3
EODNot easy, but it is doable.
The solution is to have the local socat open the remote shell (a reverse shell). Then drop into the background, whenever piped command input is detected. Finally, submit each piped command to the /dev/ptsN associated with the background socat.
The first problem is that socat always thinks it has two extra arguments whenever to try to background within in a shell script. Complaining:
socat[3124] E exactly 2 addresses required (there are 4)The second problem is that executing commands on another /dev/ptsN isn't trivial.
Consequently, the solution is in two parts:Use tmux to background the socat connection.
Use ttyecho to send each piped command to the backgrounded socat.ttyecho is a custom utility by Pratik Sinha, which also has a Rust crate.
The ttyecho command line tool is functionally similar to writevt which was part of console-tools, but as best I can tell development there has stopped, and the last Ubuntu package was for 12.04.
That means you'll very likely have to compile and install your own ttyecho.
There are some additional wrinkles - aren't there always?
Opening a new tty with tmux requires root privileges.
To be able to run:
sudo --validate
tmux ...without the launched process blocking for a password, you need to add to your /etc/sudoers.d/<user>:
Defaults: <user> !tty_ticketsWith all that in place, this should work (with ttyecho in your path)
if [ -t 0 -a $# -eq 0 ]
then
## No piped commands.
## 1. Start interactive shell.
sudo /usr/bin/nsenter --setuid 1000 \
--setgid 1000 \
--net=/var/run/netns/nns-a \
-- \
socat file:$(tty),raw,echo=0 \
tcp:10.10.10.1:2222
else
## Piped commands.
## 1. Setup sudo --validate for new tty sessions:
# Add
# Defaults: <user> !tty_tickets
# to the file (chmod 440): /etc/sudoers.d/<user>
#
sudo --validate ## 2. Start a detached connection to remote shell.
#
tmux new-session \
-d \
-s a_session \
'sudo /usr/bin/nsenter --setuid 1000 --setgid 1000 --net=/var/run/netns/nns-a -- socat file:$(tty),raw,echo=0 tcp:10.10.10.1:2222' ## 3. Capture the socat process ID
#
SOCAT_PID=$(pgrep -u "root" socat) ## 4. Get the /dev/pts of the socat connection
#
DEV_PTS=$(tmux list-panes -t a_session -F '#{pane_tty}') ## 5. Consume all the piped commands
#
while read cmd
do
sudo /usr/bin/nsenter --setuid 1000 \
--setgid 1000 \
--net=/var/run/netns/nns-a \
-- \
ttyexec -n ${DEV_PTS} "${cmd}"
done ## 6. Exit, if not already done.
#
if pgrep -u "root" socat
then
sudo /usr/bin/nsenter --setuid 1000 \
--setgid 1000 \
--net=/var/run/netns/nns-a \
-- \
ttyexec -n ${DEV_PTS} "exit"
fi
fiHope that helps someone?
|
I have a bash script that:does some thing
connects/opens a reverse shell.
does another thingmy-script contents:
#!/usr/bin/env bash# does 'some thing'sudo /usr/bin/nsenter --setuid 1000 --setgid 1000 --net=/var/run/netns/ns-a -- socat file:$(tty),raw,echo=0 tcp:10.10.10.1:2222# does 'another thing'Run interactively from the terminal this script stops and provides the remote shell for a user to interact with.
The use case is to have a single script that:accepts piped input (e.g. HEREDOC style)
when no piped-input is given, present an interactive shell.What I'd like to be able to do is use this script in batch files (piped input) as well as interactively.
The following has me stumped:
my-script <<EOCMDS
echo 1
echo 2
EOCMDS
2020/12/13 21:28:59 socat[28032] E exactly 2 addresses required (there are 4); use option "-h" for helpAppreciate any solutions you might have in mind.
Update:
This is not a question about setting up a remote shell. To avoid doubt, the remote server is setup and listening, ready to offer the (bash) shell on connection. This question concerns the client side only. To further remove doubt, while not relevant to this question, in practice the the remote server is not network-namespaced, only the local client.
| Pipe multiple commands to socat reverse shell (network-namespaced) |
With {fd}> file, the value of $fd will be greater than 9.
With system:shell-code, socat invokes sh to interpret that shell code.
sh implementations are not required to support fds above 9 in their redirection operators. Implementations such as dash or mksh don't. Also note that ksh93 (one of the three shells with zsh and bash that supports that syntax) marks the fd obtained with exec {fd}> file with the close-on-exec flag, so won't be inherited by socat there.
So, here, you'd want to use a fd below 10:
exec 4> >(my_custom_function)
socat tcp-listen:10000,reuseaddr,fork system:"head -n1>&4;echo EXIT;exit"Or invoke a shell that you know supports fds above 9 like zsh:
exec {fd}> >(my_custom_function)
socat tcp-listen:10000,reuseaddr,fork "exec:'zsh -c \"head -n1>&$fd;echo EXIT;exit\"'"(not from ksh93).
|
So i want socat to persistently listen for connections, get the first x lines and reply back with a message. Ideally i want to use a user defined function to handle that logic but i couldn't find a way to achieve that.
My scenario:
client 1:cat <(printf "line1\nline2\n") -|nc socat_server socat_portclient 2:cat <(printf "line3\nline4\n") -|nc socat_server socat_portI want to get: line1 and line3 and the clients a message (e.g. EXIT)
I've tried with:
exec {fd}> >(my_custom_function)
socat tcp-listen:10000,reuseaddr,fork system:"head -n1>&$fd;echo EXIT;exit"but i get "Bad fd number". Any ways around this?
| socat bidirectional communication with user-defined bash function |
It seems to use a little magic, but you can try inverting the two addresses so you can then add option nofork to the system command. You need to swap -u to -U of course to change direction:
socat -U PIPE:/tmp/test SYSTEM:"udevadm monitor",noforkThis seems to ignore the closing of the pipe, and you can re-open it again. Don't ask me about the magic.
|
I need to redirect output from udevadm monitor to a named pipe. For that end I use the following command:
sudo socat -u SYSTEM:"udevadm monitor" PIPE:/tmp/test &It works until a process reading from the pipe is interrupted and socat exists with a "Broken pipe" error, which is expected. However, when I list running processes it turns out that udevadm is still running.$ ps -a
PID TTY TIME CMD
3539 tty1 00:00:00 bash
3619 tty2 00:00:00 bash
3972 pts/0 00:00:00 ps
$ sudo socat -u SYSTEM:"udevadm monitor" PIPE:/tmp/test &
[1] 3973
$ ps -a
PID TTY TIME CMD
3539 tty1 00:00:00 bash
3619 tty2 00:00:00 bash
3973 pts/0 00:00:00 sudo
3974 pts/0 00:00:00 socat
3975 pts/0 00:00:00 socat
3976 pts/0 00:00:00 udevadm
3977 pts/0 00:00:00 ps
$ cat /tmp/test
monitor will print the received events for:
UDEV - the event which udev sends out after rule processing
KERNEL - the kernel uevent^C
$ 2020/06/01 12:36:06 socat[3974] E write(6, 0x1dfbc60, 147): Broken pipe[1]+ Exit 1 sudo socat -u SYSTEM:"udevadm monitor" PIPE:/tmp/test
$ ps -a
PID TTY TIME CMD
3539 tty1 00:00:00 bash
3619 tty2 00:00:00 bash
3976 pts/0 00:00:00 udevadm
3980 pts/0 00:00:00 ps
$When I replaced udevadm monitor with yes (to simply feed a stream of data to the pipe), it died along with socat.
If I simply interrupt socat with kill command, udevadm perishes neatly.
If I kill parent bash process socat and udevadm die as well, so I tried wrapping udevadm with sh -c:
sudo socat -u SYSTEM:'sh -c \"udevadm monitor\"' PIPE:/tmp/test &hoping that dying shell would kill udevadm, but to no avail.
I am aware, that orphaned process can be adopted by INIT, but it doesn't seem to be the case, because out of all processes only udevadm seems to cheat death like this. To sum up my experiments:Process tree bash->sudo->socat->udevadm - kill socat - all die
Process tree bash->sudo->socat->udevadm - broken pipe - only udevadm lives on
Process tree bash->sudo->socat->sh->udevadm - broken pipe - only udevadm lives on
Process tree bash->sudo->socat->yes- broken pipe - all die
Process tree bash->sudo->socat->udevadm - kill sudo - all die
Process tree bash->sudo->socat->udevadm - kill bash - all dieThe problem I really want to solve are lingering udevadm processes.
My preferred solution would be to udevadm die nicely along with other processes. Acceptable solution would be to have persistent pipe, which would not break when reading process dies.
Are there any options or settings I can pass either to socat or to udevadm to solve my problem?
If socat if a wrong tool for my ultimate objective to have udevadm output sent to a pipe, I am obviously open for suggestions.
| udevadm doesn't die if parent process experiences an error |
You are just missing the fork bit. The command line would then be:
socat TCP-LISTEN:8002,fork SYSTEM:/path/to/replace.shthen, the file /path/to/replace.sh should have the execution permission and could contain something like (this will change all 'a's to 'b's):
#!/bin/bashsed -u 's/a/b/g'If you are using sed, it is important to add the -u (unbuffered) flag.
|
Not sure if this belongs on here, StackOverflow, or SuperUser.
I have a device running a reverse telnet server that I need to be able to send/receive data to. I'm able to play with it if I run socat like so and telnet into port 8002:
sudo socat TCP-LISTEN:8001 TCP-LISTEN:8002However, it sends information it shouldn't, and I'm trying to use sed to filter this data out. I'd like this communication to remain bi-directional (that is, anything I type into telnet on localhost:8002 gets sent out through localhost:8001 and vise versa).
I've tried using a bash script containing:
#!/bin/bash
sed (my regex here) | socat - TCP-LISTEN:8002and then running:
sudo socat TCP-LISTEN:8001 SYSTEM:./replace.shBut that outputs nothing in the telnet console. I've also tried EXEC: to the same nothing happening.
I've even tried:
sudo socat TCP-LISTEN:8001 "SYSTEM:'sed (my regex here)' || TCP-LISTEN:8002"to no effect.
| Sed with port forwarding in socat? |
You have set up a listening datagram socket with socat+UNIX-RECV: and are attempting to talk to it via a stream socket with nc.
The second scenario works because in that case you added the missing -u flag to nc, so that both it and socat were employing a datagram socket. It wasn't anything to do with there being a proxy.
Further readinghttps://unix.stackexchange.com/a/294221/5132 |
I'm trying to debug why data isn't being sent over a Unix Domain Socket.
I have 2 applications which should be communicating over a UDS but aren't.
To test I've done the following:
Using socat, I listen on a socket like this:
socat -x -u UNIX-RECV:/tmp/dd.sock STDOUT
and using netcat to send data like this:
echo "hello" | nc -U -w1 /tmp/dd.sock
nothing happens.
But if I also set up socat as a proxy, to listen to a UDP port, and write that to the socket like this:
socat -s -u UDP-RECV:9988 UNIX-SENDTO:/tmp/dd.sock
Then sending via netcat to the UDP port works:
echo "Hello" | nc -u localhost 9988
I've also been able to get my client application to write UDP to the proxy and it's successful where is wasn't when writing to the unix socket.
I would like to understand why socat doesn't receive data written to it by nc, but does if I proxy over UDP.
Using Amazon Linux
4.14.101-75.76.amzn1.x86_64
| Sending data to Unix socket failing unless proxied with socat via UDP |
To see how to setup socat via scripts, please see this post and this gist:
Intercept communications on physical serial port using socat
https://gist.github.com/krzyklo/e60793b27400be7a330042aa6bdf388a
socat -x -d -d pty,raw,echo=0,link=/tmp/cryocon_simulator pty,raw,echo=0,link=/tmp/cryocon
Below scripts from links, to have all in one place:
my-serial.py
import sys
import serial
DEFAULT_ADDR = '/home/krzys/myserial'
DEFAULT_CMD = 'R5'
args = len(sys.argv) - 1
if args == 0:
addr, cmd = DEFAULT_ADDR, DEFAULT_CMD
elif args == 1:
addr, cmd = DEFAULT_ADDR, sys.argv[1]
else:
addr, cmd = sys.argv[1:3]cmd += '\r\n'
s = serial.Serial("/home/krzys/myserial",9600,timeout=0.5)
s.write(cmd.encode())
print(s.readline())client.py
import sys
import serial
DEFAULT_ADDR = '/tmp/cryocon'
DEFAULT_CMD = '*IDN?'
args = len(sys.argv) - 1
if args == 0:
addr, cmd = DEFAULT_ADDR, DEFAULT_CMD
elif args == 1:
addr, cmd = DEFAULT_ADDR, sys.argv[1]
else:
addr, cmd = sys.argv[1:3]cmd += '\n'
s = serial.serial_for_url(addr)
s.write(cmd.encode())
print(s.readline())simulator.py
import sys
import loggingimport serialDEFAULT_ADDR = '/tmp/cryocon_simulator'logging.basicConfig(level=logging.INFO)addr = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_ADDRconn = serial.serial_for_url(addr)
logging.info(f'Ready to receive requests on {addr}')
while True:
request = conn.readline()
logging.info('REQ: %r', request)
request = request.strip().decode().lower()
reply = 'Cryo-con,24C,305682,1.05A\n' if request == '*idn?' else 'NACK\n'
reply = reply.encode()
logging.info('REP: %r', reply)
conn.write(reply) |
I want to use socat to direct serial commands over ethernet
to anethernet-serial converter (static IP address).
Iam wondering what would be a good way of starting socat.
As I understand it, systemd would allow me
toensure socat is always running – or in case of failure, tries to restart.
The .service file would look like:
[Service]
Type=simple
Restart=always
RestartSec=5[Unit]
Description=my socat test
User=me
Group=meExecStart=/bin/bash -c '~/my_socat.sh'[Install]
WantedBy=multi-user.targetThe script would look like:
#!/bin/bash
socat PTY,link=/home/me/dev/valve1 TCP:192.168.11.101:5001 & socat PTY,link=/home/me/dev/valve2 TCP:192.168.11.101:5002Would this approach do what I want?
Would socat be restarted if it dies for some reason?
And what would happen if the ethernet connection
is not available when socat is started?
Running it from the shell without network connection does not work,
andthecommand fails with the error message "network is unreachable".
How should Imake sure socat is running
before my (Python) script is executed?
Should Istart socat from within Python?
| socat: call from script, bashrc or systemd? |
AFAIK this is not possible with current versions
|
I'm using this instruction to forward a port to another, both on a local machine:
socat -d -d TCP4-LISTEN:80,reuseaddr,fork TCP4:127.0.0.1:8000I need to keep the port open unless the destination port get closed (connection refuse).
Is it possible to ask socat to terminate on connection refuse (with fork enabled)?
| tell socat to stop on connection refuse with fork enabled |
Hi if you want check connection between server with socat try below command and refer link ..
CWsocat [options] <address> <address>
CWsocat -V
CWsocat -h[h[h]] | -?[?[?]]
CWfilan
CWprocantry this link for better understanding..
there are other method to check the connectivity..
|
I want to get the behavior of "nc -z host port ; echo $?" with socat, since my network admins have disabled netcat. The purpose is just to test that a TCP connection is open between two servers. How would I go about doing this?
| How to “nc -z <address>” with socat? |
The problem was that I forgot to include ",pty" as an option for EXEC:"/usr/sbin/pppd ..." so pppd was silently crashing.
|
I am running NetBSD 6.1.4, and I have an stunnel instance with the following configuration:
[https service]
accept = 443
CAfile = /u01/usbtether/CA/certs/rootCA.crt
cert = /usr/pkg/etc/stunnel/stunnel.pem
pty = yes
exec = /usr/sbin/pppd
execargs = pppd call phone
verify = 2
client = noEverything works nicely, except for an ever increasing rx error count on the other side. I want to compare the ppp traffic before and after it leaves the stunnel. My strategy thus far is to use socat. I changed the exec lines to point to a shell script like
#!/bin/sh
socat -,echo=0,raw SYSTEM:'tee /root/pppd-in.log | socat -,echo=0,raw EXEC:"/usr/sbin/pppd call phone" | tee /root/pppd-out.log'But I cannot seem to get my ducks in a row. I've managed to loopback everything the other pppd sends, or ignore everything the other pppd sends, but I cannot get the syntax right to actually pass the data between stunnel and pppd while also dumping input and output to a file(although I only care about output).
I've also tried
#!/bin/sh
/usr/sbin/pppd call phone | tee /root/serial-out.logBut I just seem to send gibberish back to the calling pppd (I assume the pipe through tee is like not including raw in socat?).
So what is the best way to snoop on the data in a PTY?
For added interest, the data I receive on the other side of the stunnel is occasionally scrambled a little bit. For example, I may receive a ppp frame with an IP packet of length 100, followed by a 0x7e, and 10 additional bytes. Another frame, (which may have arrived several frames before or after the frame with extra bytes) will arrive with an IP packet that is missing 8 bytes. If I were to take that extra chunk and tack it onto the end, I would have, presumably, the correct IP packet plus the FCS. My intention with the PTY snoop is to verify if pppd is sending the data like that (since the missing chunk is always preceded by a 0x7e byte, I think this is likely), or if something weird is happening in transit.
| How to capture data transferred on a PTY? |
Sounds like you'd rather want:
socat -u udp-recvfrom:10,fork exec:scripts/pi-wol.shFor upon every received UDP packet, fork a process to handle it and send the contents of the packet on the stdin of a new invocation of that script.
-u for unidirectional unless you want the output of the script to be sent back as UDP packets to the client.
|
I have a RPi 1b+ v1.2 with Raspberry Pi OS June 2021.
I'm using socat to trigger a bash script that wakes another PC in the network up. I use this command:
sudo socat UDP-LISTEN:10 EXEC:scripts/pi-wol.sh,forkbut in throws an error
2021/09/05 19:26:38 socat[1743] E parseopts(): option "fork" not supported with this address typeIt works fine without fork but only once and I need it to constantly listen. Any ideas how can I do that?
| Make "socat" constantly listen for the magic packet |
Your quotes are not affecting the $(date) command, so it's always evaluated exactly once immediately before the socat command is executed.
Simplifying your command for illustrative purposes here's what I hope is a slightly easier view that shows how $(date) isn't inside quotes
socat TCP4-LISTEN:flags SYSTEM:"sed | gpcl6 file-"$(date)"-suffix"
# ^in quotes ^out ^in ^outIf you put it inside double-quotes it will be evaluated just like now (except that any spaces in the resulting output will remain as spaces rather than word split points). If you put it inside single-quotes, the shell that socat calls to evaluate the SYSTEM option will evaluate it each time it's called:
socat TCP4-LISTEN:flags SYSTEM:'sed | gpcl6 file-$(date)-suffix'You can see this in action with this pair of commands, run on two different systems:
# Server
socat TCP4-LISTEN:4178,fork,reuseaddr SYSTEM:'cat >socat.$(date +%H%M%S).txt'# Client
echo boo | nc remoteServer 4178# Sever
ls șocat.*.txtPutting this change back into your original code you should get this (notice that for convenience I also swapped the type of quotes used by the sed command):
HPNP=4178 socat TCP4-LISTEN:4178,bind=192.168.216.179,fork,reuseaddr,su=hp3000 SYSTEM:'sed -r "1s/^.{42}//" | cat /var/spool/hp3000/forms/hll_inv_ljiii_85.ovl - | gpcl6 -dNOSAFE -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=/var/spool/hp3000/np4178/HP3000-INV-$(date -Iseconds)-%03u.pdf -' & |
OS FreeBSD-12.2
I have a virtual printer setup using socat. The socat command runs in the background. It spawns a system shell that processes the input stream and sends it to gpcl6 to create pdf documents. The output goes to a file in a specific directory. The file name is meant to contain a timestamp $(date -Iseconds). The problem is that this timestamp is only evaluated when the socat command is started and not thereafter. My question is: Is there a way to make this re-evaluation happen each time a data stream arrives?
The full command is:
HPNP=4178 socat TCP4-LISTEN:4178,bind=192.168.216.179,fork,reuseaddr,su=hp3000 SYSTEM:"sed -r '1s/^.{42}//' | cat /var/spool/hp3000/forms/hll_inv_ljiii_85.ovl - | gpcl6 -dNOSAFE -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=/var/spool/hp3000/np4178/HP3000-INV-"$(date -Iseconds)"-%03u.pdf -" &
I have experimented with single, double, and no quotes. The command launches with all three options. However, single and double quote produce the same results, the timestamp is fixed to the time the command was started. Without quotes the command launches but anything sent to it results in a constant stream of broken pipe errors:
2021/05/17 15:56:55 socat[17557] E write(5, 0x800b09000, 1460): Broken pipe
cat: stdout: Broken pipe
sed: stdout: Broken pipeThe socat man page has this to say:
SYSTEM:<shell-command>
Forks a sub process that establishes communication with its
parent process and invokes the specified program with system() .
Please note that <shell-command> [string] must not contain ','
or "!!", and that shell meta characters may have to be
protected. After successful program start, socat writes data to
stdin of the process and reads from its stdout.
Option groups: FD,SOCKET,EXEC,FORK,TERMIOS
Useful options: path, fdin, fdout, chroot, su, su-d, nofork,
pty, stderr, ctty, setsid, pipes, sigint, sigquit
See also: EXECI gather from this that a shell is forked but once on startup. Is that the reason the $() construct is not being evaluated each time a data stream arrives? Is there anyway around this limitation?
| How to get bash to reevaluate $(date) when part of a background job - if possible |
To achieve the same behavior of nc -u -s 192.168.0.1 -p 8888 192.168.0.2 9999 using socat:
$ socat - UDP4:192.168.0.2:9999,bind=192.168.0.1:8888 |
How do I specify source port in socat?
In netcat I can simply:
nc -u -s 192.168.0.1 -p 8888 192.168.0.2 9999I tried
socat udp4:192.168.0.2:9999 STDIN:192.168.0.1:8888It's failed
STDIN: wrong number of parameters (2 instead of 0)So how do I do it in socat?
| Socat specify source port |
Is this type of duplex communication possible with socat at all (in best case without opening a new port)?No; but that has nothing to do with socat. A TCP connection gets closed and then can't be used anymore. But your mechanism, and specifically cat - as Stéphane pointed out, rely on the connection being closed.Shell is Bash, no ZSH avaiable. Vanilla Python can also be used.So, vanilla Python.
From Python documentation on included modules, really only very slightly modified:
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandlerPORT = 8000class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)with SimpleXMLRPCServer(('localhost', PORT),
requestHandler = RequestHandler,
use_builtin_types = True) as server:
server.register_introspection_functions() # Register a function under function.__name__.
@server.register_function
def convert(target_format: str, img: bytes):
# do something with img instead of just returning it,
# but you get the idea.
return img @server.register_function
def length(img: bytes):
return len(img) server.serve_forever()on the client end,
import xmlrpc.clientPORT = 8000server_handle = xmlrpc.client.ServerProxy(f'http://localhost:{PORT:d}',
use_builtin_types = True)with open("inputimage.jpg", "rb") as infile:
converted = server_handle.convert("image/png", infile.read())with open("outputimage.png", "wb") as outfile:
outfile.write(converted)# Print list of available methods
print(server_handle.system.listMethods())Note that this is absolutely vanilla python. xmlrpc.server isn't any less included in standard python than say, socket or math.We can stretch the vanilla concept a bit from there; venv is also part of Python's standard library. Soooo if all you have is standard Python:
python3 -m venv serverstuff
. serverstuff/bin/activate
pip install Flaskgives you a bit more comfort. You can then write a server that looks like the quickstart example:
from flask import Flask
from flask import request
from flask import Responseapp = Flask(__name__)@app.route("/")
def say_hello():
return "helloo"@app.route("/convert/<target_fmt>"):
def convert(target_fmt):
print(target_fmt)
try:
infile = request.files["file"]
except Exception as e:
print(e)
return Response(response="", status=406)
# convert it; infile is a Werkzeug.Filestorage
# https://werkzeug.palletsprojects.com/en/2.3.x/datastructures/#werkzeug.datastructures.FileStorage
data = infile.read()
return Response(response=data, mimetype=f"image/{target_fmt}", status=200)save to server.py and run as python3 -m flask --app server run --port 8000.
and the client is then super easy in shell scripting:
$ myfiletoupload=/home/mosaic/catpicture.jpg
$ curl http://127.0.0.1:8000/convert/png -F "file=@${myfiletoupload}" |
I would like to create a TCP connection to a remote server with socat, where a client sendsan action for an image file ("convert", "open", etc.)
the image (binary content) itselfServer will then process the image with given action.
My first idea has been to pass this text action type before the binary content:
# client
socat tcp:server:9999 -\
< <(echo "open"; cat path/to/imgfile)# server
socat tcp-listen:9999 - | {
IFS= read -r action
cat - > /tmp/imgfile
# do process image file with action type ...
}This seems to work for particular case, but is inflexible, e.g. when needing to pass multiple arguments. Also prepending text before binary content makes me think, the image file potentially could be damaged?
Hence I am trying to find a cleaner solution, passing both arguments one by one (here referred to as duplex communication):My attempt so far, not being an expert on socat:
# client
socat\
tcp:server:9999\
system:'echo "open"; IFS= read -r ack; cat path/to/image.png'# server
socat tcp-listen:9999\
system:'IFS= read -r action; echo "ACK"; binary=$(cat -); echo "process image with action now..."'which currently gets meBroken pipeIs this type of duplex communication possible with socat at all (in best case without opening a new port)?
Have I overseen a simpler alternative?
I probably should have said, this is to be done in the most simplest/vanilla way possible, no further use of frameworks, no HTTP server overhead if possible. Shell is Bash, no ZSH avaiable. Vanilla Python can also be used.
| socat: How to do simple duplex communication with shell? |
Thanks Kamil for your explanation. I ended up fixing it by monitoring the status of the socat pid to become 'S'.
Here's my fixed code.
# fetch uploaded text from termbin.comurl=$1# check if url is provided as argument
if [[ $# -lt 1 ]]; then
echo "error: provide url" >&2
echo >&2
echo "Usage: fetch.sh [url]" >&2
exit 1
fin1=$'\r\n'
request=$(cat <<END
GET /${url}/ HTTP/1.1
Host: termbin.com
Connection: close
$n1
$n1
END
)
#echo "$request"socat TCP-LISTEN:8080,fork,reuseaddr ssl:termbin.com:443,verify=0 &
socat_pid=$!# loop until socat's pid status becomes 'S'
while [[ -z $(ps -p $socat_pid -o stat --no-headers | grep 'S') ]]; do
:
doneexec 3<>/dev/tcp/localhost/8080
echo "$request" >&3
cat <&3# if socat's pid status is 'S' then kill it
if [[ -n $(ps -p $socat_pid -o stat --no-headers | grep 'S') ]]; then
kill -9 $socat_pid
fiexec 3>&- |
I'm trying to fetch a page from https://termbin.com/9hc2k using bash redirections and socat, especially using special file /dev/tcp/localhost/8080 to open a network connection.
# fetch.sh
# fetch uploaded text from termbin.comurl=$1# check if url is provided as argument
if [[ $# -lt 1 ]]; then
echo "error: provide url" >&2
echo >&2
echo "Usage: fetch.sh [url]" >&2
exit 1
fin1=$'\r\n'
request=$(cat <<END
GET /${url}/ HTTP/1.1
Host: termbin.com
Connection: close
$n1
$n1
END
)
#echo "$request"socat TCP-LISTEN:8080,fork,reuseaddr ssl:termbin.com:443,verify=0 &
socat_pid=$!
exec 3<>/dev/tcp/localhost/8080
echo "$request" >&3
cat <&3exec 3>&-If I try to fetch https://termbin.com/9hc2k:
$ ./fetch.sh 9hc2k
./fetch.sh: connect: Connection refused
./fetch.sh: line 26: /dev/tcp/localhost/8080: Connection refused
./fetch.sh: line 27: 3: Bad file descriptor
./fetch.sh: line 28: 3: Bad file descriptorFirst time I get Connection refused error.
If I try again however,
$ ./fetch.sh 9hc2k
2022/07/30 12:29:18 socat[497218] E bind(5, {AF=2 0.0.0.0:8080}, 16): Address already in use
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 30 Jul 2022 02:29:20 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 6
Last-Modified: Sat, 30 Jul 2022 01:51:42 GMT
Connection: close
ETag: "62e48eae-6"
Accept-Ranges: byteshelloAs you can see the second time of trying it works. I have fetched text hello from the link.
I don't know why it fails the first time and then second time (and subsequent) around it works. Can you tell me why this is so and what is the most rational fix? Thanks.
| Proxying localhost to HTTPS using socat returns Connection refused first time |
Use the bind option instead of sourceport:
$ echo hello | socat - UDP-DATAGRAM:192.168.1.255:11111,broadcast,bind=:22222I'm not sure why sourceport doesn't work in this case, since it clearly does for e.g. UDP-CONNECT...but it's also not clear why there's a separate sourceport option when bind already does the same thing.
|
I am trying to send a udp packet from a specific port:
$ echo hello | socat - UDP-DATAGRAM:192.168.1.255:11111,broadcast,sourceport=22222But a random port is used instead:
# tcpdump -vvvv -ttttt -nienp0s31f6 udp
tcpdump: listening on enp0s31f6, link-type EN10MB (Ethernet), snapshot length 262144 bytes
00:00:00.000000 IP (tos 0x0, ttl 64, id 40649, offset 0, flags [DF], proto UDP (17), length 34)
192.168.1.17.35829 > 192.168.1.255.11111: [udp sum ok] UDP, length 6How can I send a (broadcast) udp packet from a specific port?
N.B. I also tried sending a unicast udp packet with socat, but sourceport wasn't honored there either.
| socat does not honor sourceport option |
Try adding -n to your echo or using printf
$ echo -e '\xFF\x01' | xxd -p
ff010a
$ echo -en '\xFF\x01' | xxd -p
ff01
$ printf '\xFF\x01' | xxd -p
ff01As I think you realize, 0A is the newline character. See also: https://www.asciitable.com/
|
I try to send a udp broadcast with 2 (FF 01) bytes over bash, but in my network sniffer I notice it's 3 bytes. FF 01 0A where does the line break come from and how can i prevent it?
echo -e '\xFF\x01' | socat - udp-datagram:255.255.255.255:1500,bind=:6666,broadcast,reuseaddr | send udp broadcast via bash |
Actually I found this workaround
ssh -X -C 192.168.201.200 -t /usr/X11/bin/amd64/Xephyr :1 -query localhost |
I want to tunnel via ssh a Xdmcp protocol. To access sicure to a remote login.
An easy solution can be openvpn, but I want to try socat+ssh first.
The server is Solaris 10 The client is Slackware 15.
On Client
ssh -L 6667:localhost:6667 192.168.201.200on server
socat tcp4-listen:6667,reuseaddr,fork UDP:192.168.201.200:177on Client
sudo socat udp4-listen:177,reuseaddr,fork tcp:localhost:6667Now on client i run Xephyr and...
Xephyr -query localhost -screen 1024x767 :2Using Xdcmp directly without tunnel works, but is unsafe
| Why the tunnel Xdmcp+ssh don't work? |
Multicasting is behaving as it is supposed to work.
When you are signaling an interface to listen for a multicast address, in fact, you are associating the underlying interface with that address and not the IP address of that interface.
So as long as you are sharing the same physical/virtual medium/network, all the interfaces associated with the multicast address will receive a multicast transmission.
|
I'm a linux beginner and trying to test multicast with socat on Ubuntu which works.
A bit "too well" actually (or I'm misunderstanding something fundamental)
my network looks that (ifconfig, abbreviated)
ens33 - 192.168.2.10
lo - 127.0.0.1
vboxnet0 - 5 - 192.168.56.1 and up to 192.168.1.1
vboxnet6 - 192.168.1.1
vboxnet7 - 10.0.1.1
vboxnet8 - 192.88.99.1I start socat in two consoles like that
receiver
socat -d -d UDP-RECVFROM:6666,ip-add-membership=233.168.0.100:192.68.56.1:ens33,fork EXEC:hostname
sender
socat -d -d STDIO UDP4-DATAGRAM:233.18.0.100:6666,range=192.168.56.100/30
It doesn't matter what I choose as multicast address, as long as they match.
And I have to specify the interface on the receiver side for it to work.
Like I said at the beginning the receiver receives messages and that's the problem.
If I'm not mistaken it shouldn't because it is not i the defined range of 192.168.56.100/30 which translates to 192.168.56.101 - 192.168.56.103
the receiver always receives packages no matter what IP.
Am I misunderstanding what range actually does?
What am I missing?
I suspect it has something to with being on the same device (routing).
| how to test multicast with socat on one machine |
socat tcp-listen:6697 openssl-connect:irc.freenode.net:6697
and then
sic -h 127.0.0.1 -p 6697 -n your-nickname
But really you shouldn't be using sic unless you have a specialized need.
Try irssi instead -- it will save you much time and provide many features that sic does not.
Once open, you can just run /connect -ssl irc.freenode.net 6697, being sure to replace with your own connection details. You can also create custom configurations to auto-connect to various servers and channels on start-up.
|
Recently, I got into irc, so I installed sic and started - obviously - chatting.
But, it turns out that sic doesn't provide any security features like SSL or TCP so I in man sic, they told to use socat to establish a secure TCP connection so I installed it and read the documentary.
In the example section, I found this:socat TCP-LISTEN:www TCP:www.domain.org:wwwSo I just ran socat tcp-listen:6667,fork tcp:irc.freenode.net:6697and tried to connect with it using sic -h 127.0.1 -p 6667 which puked out:sic: remote host closed connectionwith socat not complaining.I tried it again with the option -d -d for socat being more verbose:
2019/01/02 00:38:38 socat[1889] N accepting connection from AF=2
127.0.0.1:38664 on AF=2 127.0.0.1:6667
2019/01/02 00:38:38 socat[1889] N forked off child process 1897
2019/01/02 00:38:38 socat[1889] N listening on AF=2 0.0.0.0:6667
2019/01/02 00:38:38 socat[1897] N opening connection to AF=2
185.30.166.37:6697
2019/01/02 00:38:38 socat[1897] N successfully connected from local
address AF=2 192.168.178.28:42822
2019/01/02 00:38:38 socat[1897] N starting data transfer loop with FDs
[6,6] and [5,5]
2019/01/02 00:38:38 socat[1897] W read(5, 0x558eefca3710, 8192):
Connection reset by peer
2019/01/02 00:38:38 socat[1897] N socket 2 to socket 1 is in error
2019/01/02 00:38:38 socat[1897] N socket 2 (fd 5) is at EOF
2019/01/02 00:38:38 socat[1897] N socket 1 (fd 6) is at EOF
2019/01/02 00:38:38 socat[1897] N socket 2 (fd 5) is at EOF
2019/01/02 00:38:38 socat[1897] N exiting with status 0
2019/01/02 00:38:38 socat[1889] N childdied(): handling signal 17 | Using socat to make a secure tcp connection to an irc server |
According to the comments, socat always reads and forwards data as soon as it is available on the file descriptor and this behaviour is not meant to be configurable.
So, this is dependent on the kernel and the type of (device) file or underlying driver and not controlled by socat itself.
|
I am using socat to forward incoming serial traffic to a local UDP port (on macOS):
socat OPEN:/dev/cu.usbmodem13203 UDP:localhost:12345I consider a serial device being a streaming interface while UDP is packet-based so there exists no definitive right answer where or how to introduce packet boundaries. In my test, every single byte is forwarded as its own UDP packet. For example, when sending the string "XYZ", my test server outputs:
Datagram: X
Datagram: Y
Datagram: ZWhy is the byte sequence split into several packets at all and what is the mechanism behind it? Is there any way to control that behaviour?
| Where/How does socat insert packet boundaries? |
Closest Websocat command line is something like this:
websocat --restrict-uri /vless-ws -bE ws-l:0.0.0.0:8080 --binary-prefix B --text-prefix T ws://127.0.0.1:19002But there are many imperfections:Disconnections get detected late
Ping replies get replied by Websocat, not by final endpoint
Message size is limited by Websocat buffer size
X-Real-IP is not filled in
Only /vless-ws would match, not /vless-ws/ or /vless-ws/something.Why don't just expose 127.0.0.1:19002 directly as port 8080 instead? Are there other things in Nginx config file that are not depicted here?
Note that you can also use Caddy instead of Nginx - it is easy to run it ad-hoc, as non-root, with only a one simple config file, for example:
{
admin off
}
:8080handle_path /vless-ws/* {
reverse_proxy http://127.0.0.1:19002
}Obviously, Websocket connections would get forwarded, you don't need to specify those headers manually.I'm sure websocat can do that since it has many options.Websocat (at least as of version 1) is not designed for handling different incoming URLs differently, except of some exceptions like --restrict-uri or -F options.
It is expected that user also uses other tools like a web server or plain socat for missing things. Some examples of combining Websocat with other tools are documented in moreexamples.md.
|
I have this nginx custom configuration:
server {
listen 8080;
server_name subdomain.domain.my.id;
location /vless-ws { # Consistent with the path of V2Ray configuration
if ($http_upgrade != "websocket") { # Return 404 error when WebSocket upgrading negotiate failed
return 404;
}
proxy_redirect off;
proxy_pass http://127.0.0.1:19002;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}Here is long option for websocat:
(base) isysrg@isysresearch:~/tmp$ ./websocat --help=long option
websocat 1.12.0
Vitaly "_Vi" Shukela <[emailprotected]>
Command-line client for web sockets, like netcat/curl/socat for ws://.USAGE:
websocat ws://URL | wss://URL (simple client)
websocat -s port (simple server)
websocat [FLAGS] [OPTIONS] <addr1> <addr2> (advanced mode)FLAGS:
--stdout-announce-listening-ports [A] Print a line to stdout for each port being listened
--async-stdio [A] On UNIX, set stdin and stdout to nonblocking mode instead of
spawning a thread. This should improve performance, but may break other
programs running on the same console.
--compress-deflate [A] Compress data coming to a WebSocket using deflate method. Affects
only binary WebSocket messages.
--compress-gzip [A] Compress data coming to a WebSocket using gzip method. Affects only
binary WebSocket messages.
--compress-zlib [A] Compress data coming to a WebSocket using zlib method. Affects only
binary WebSocket messages.
--dump-spec [A] Instead of running, dump the specifiers representation to stdout
-e, --set-environment Set WEBSOCAT_* environment variables when doing exec:/cmd:/sh-c:
Currently it's WEBSOCAT_URI and WEBSOCAT_CLIENT for
request URI and client address (if TCP)
Beware of ShellShock or similar security problems.
-E, --exit-on-eof Close a data transfer direction if the other one reached EOF
--foreachmsg-wait-read [A] Wait for reading to finish before closing foreachmsg:'s peer
--jsonrpc Format messages you type as JSON RPC 2.0 method calls. First word
becomes method name, the rest becomes parameters, possibly automatically
wrapped in [].
--jsonrpc-omit-jsonrpc [A] Omit `jsonrpc` field when using `--jsonrpc`, e.g. for Chromium
--just-generate-key [A] Just a Sec-WebSocket-Key value without running main Websocat
--linemode-strip-newlines [A] Don't include trailing \n or \r\n coming from streams in WebSocket
messages
-0, --null-terminated Use \0 instead of \n for linemode
--no-line [A] Don't automatically insert line-to-message transformation
--no-exit-on-zeromsg [A] Don't exit when encountered a zero message. Zero messages are used
internally in Websocat, so it may fail to close connection at all.
--no-fixups [A] Don't perform automatic command-line fixups. May destabilize
websocat operation. Use --dump-spec without --no-fixups to discover what
is being inserted automatically and read the full manual about Websocat
internal workings.
--no-async-stdio [A] Inhibit using stdin/stdout in a nonblocking way if it is not a tty
-1, --one-message Send and/or receive only one message. Use with --no-close and/or -u/-U.
--oneshot Serve only once. Not to be confused with -1 (--one-message)
--print-ping-rtts Print measured round-trip-time to stderr after each received WebSocket
pong.
--exec-exit-on-disconnect [A] Make exec: or sh-c: or cmd: immediately exit when connection is
closed, don't wait for termination.
--exec-sighup-on-stdin-close [A] Make exec: or sh-c: or cmd: send SIGHUP on UNIX when input is
closed.
--exec-sighup-on-zero-msg [A] Make exec: or sh-c: or cmd: send SIGHUP on UNIX when facing incoming
zero-length message.
-q Suppress all diagnostic messages, except of startup errors
--reuser-send-zero-msg-on-disconnect [A] Make reuse-raw: send a zero-length message to the peer when some
clients disconnects.
-s, --server-mode Simple server mode: specify TCP port or addr:port as single argument
-S, --strict strict line/message mode: drop too long messages instead of splitting
them, drop incomplete lines.
--timestamp-monotonic [A] Use monotonic clock for `timestamp:` overlay
-k, --insecure Accept invalid certificates and hostnames while connecting to TLS
--udp-broadcast [A] Set SO_BROADCAST
--udp-multicast-loop [A] Set IP[V6]_MULTICAST_LOOP
--udp-oneshot [A] udp-listen: replies only one packet per client
--udp-reuseaddr [A] Set SO_REUSEADDR for UDP socket. Listening TCP sockets are always
reuseaddr.
--uncompress-deflate [A] Uncompress data coming from a WebSocket using deflate method.
Affects only binary WebSocket messages.
--uncompress-gzip [A] Uncompress data coming from a WebSocket using deflate method.
Affects only binary WebSocket messages.
--uncompress-zlib [A] Uncompress data coming from a WebSocket using deflate method.
Affects only binary WebSocket messages.
-u, --unidirectional Inhibit copying data in one direction
-U, --unidirectional-reverse Inhibit copying data in the other direction (or maybe in both directions
if combined with -u)
--accept-from-fd [A] Do not call `socket(2)` in UNIX socket listener peer, start with
`accept(2)` using specified file descriptor number as argument instead
of filename
--unlink [A] Unlink listening UNIX socket before binding to it
-V, --version Prints version information
-v Increase verbosity level to info or further
-b, --binary Send message to WebSockets as binary messages
-n, --no-close Don't send Close message to websocket on EOF
--websocket-ignore-zeromsg [A] Silently drop incoming zero-length WebSocket messages. They may
cause connection close due to usage of zero-len message as EOF flag
inside Websocat.
-t, --text Send message to WebSockets as text messages
--base64 Encode incoming binary WebSocket messages in one-line Base64 If
`--binary-prefix` (see `--help=full`) is set, outgoing WebSocket
messages that start with the prefix are decoded from base64 prior to
sending.
--base64-text [A] Encode incoming text WebSocket messages in one-line Base64. I don't
know whether it can be ever useful, but it's for symmetry with
`--base64`.OPTIONS:
--socks5 <auto_socks5>
Use specified address:port as a SOCKS5 proxy. Note that proxy authentication is not supported yet. Example:
--socks5 127.0.0.1:9050
--autoreconnect-delay-millis <autoreconnect_delay_millis>
[A] Delay before reconnect attempt for `autoreconnect:` overlay. [default: 20] --basic-auth <basic_auth>
Add `Authorization: Basic` HTTP request header with this base64-encoded parameter --queue-len <broadcast_queue_len>
[A] Number of pending queued messages for broadcast reuser [default: 16] -B, --buffer-size <buffer_size> Maximum message size, in bytes [default: 65536]
--byte-to-exit-on <byte_to_exit_on>
[A] Override the byte which byte_to_exit_on: overlay looks for [default: 28] --client-pkcs12-der <client_pkcs12_der> [A] Client identity TLS certificate
--client-pkcs12-passwd <client_pkcs12_passwd>
[A] Password for --client-pkcs12-der pkcs12 archive. Required on Mac. --close-reason <close_reason>
Close connection with a reason message. This option only takes effect if --close-status-code option is
provided as well.
--close-status-code <close_status_code> Close connection with a status code.
-H, --header <custom_headers>...
Add custom HTTP header to websocket client request. Separate header name and value with a colon and
optionally a single space. Can be used multiple times. Note that single -H may eat multiple further
arguments, leading to confusing errors. Specify headers at the end or with equal sign like -H='X: y'.
--server-header <custom_reply_headers>...
Add custom HTTP header to websocket upgrade reply. Separate header name and value with a colon and
optionally a single space. Can be used multiple times. Note that single -H may eat multiple further
arguments, leading to confusing errors.
--exec-args <exec_args>...
[A] Arguments for the `exec:` specifier. Must be the last option, everything after it gets into the exec
args list.
--header-to-env <headers_to_env>...
Forward specified incoming request header to H_* environment variable for `exec:`-like specifiers. -h, --help <help>
See the help.
--help=short is the list of easy options and address types
--help=long lists all options and types (see [A] markers)
--help=doc also shows longer description and examples.
--inhibit-pongs <inhibit_pongs>
[A] Stop replying to incoming WebSocket pings after specified number of replies --just-generate-accept <just_generate_accept>
[A] Just a Sec-WebSocket-Accept value based on supplied Sec-WebSocket-Key value without running main
Websocat
--max-messages <max_messages>
Maximum number of messages to copy in one direction. --max-messages-rev <max_messages_rev>
Maximum number of messages to copy in the other direction. --conncap <max_parallel_conns>
Maximum number of simultaneous connections for listening mode --max-sent-pings <max_sent_pings>
[A] Stop sending pings after this number of sent pings --max-ws-frame-length <max_ws_frame_length>
[A] Maximum size of incoming WebSocket frames, to prevent memory overflow [default: 104857600] --max-ws-message-length <max_ws_message_length>
[A] Maximum size of incoming WebSocket messages (sans of one data frame), to prevent memory overflow
[default: 209715200]
--origin <origin> Add Origin HTTP header to websocket client request
--pkcs12-der <pkcs12_der>
Pkcs12 archive needed to accept SSL connections, certificate and key.
A command to output it: openssl pkcs12 -export -out output.pkcs12 -inkey key.pem -in cert.pem
Use with -s (--server-mode) option or with manually specified TLS overlays.
See moreexamples.md for more info.
--pkcs12-passwd <pkcs12_passwd>
Password for --pkcs12-der pkcs12 archive. Required on Mac. -p, --preamble <preamble>...
Prepend copied data with a specified string. Can be specified multiple times. -P, --preamble-reverse <preamble_reverse>...
Prepend copied data with a specified string (reverse direction). Can be specified multiple times. --request-header <request_headers>...
[A] Specify HTTP request headers for `http-request:` specifier. -X, --request-method <request_method> [A] Method to use for `http-request:` specifier
--request-uri <request_uri> [A] URI to use for `http-request:` specifier
--restrict-uri <restrict_uri>
When serving a websocket, only accept the given URI, like `/ws`
This liberates other URIs for things like serving static files or proxying.
-F, --static-file <serve_static_files>...
Serve a named static file for non-websocket connections.
Argument syntax: <URI>:<Content-Type>:<file-path>
Argument example: /index.html:text/html:index.html
Directories are not and will not be supported for security reasons.
Can be specified multiple times. Recommended to specify them at the end or with equal sign like `-F=...`,
otherwise this option may eat positional arguments
--socks5-bind-script <socks5_bind_script>
[A] Execute specified script in `socks5-bind:` mode when remote port number becomes known. --socks5-destination <socks_destination>
[A] Examples: 1.2.3.4:5678 2600:::80 hostname:5678 --tls-domain <tls_domain>
[A] Specify domain for SNI or certificate verification when using tls-connect: overlay --udp-multicast <udp_join_multicast_addr>...
[A] Issue IP[V6]_ADD_MEMBERSHIP for specified multicast address. Can be specified multiple times. --udp-multicast-iface-v4 <udp_join_multicast_iface_v4>...
[A] IPv4 address of multicast network interface. Has to be either not specified or specified the same number
of times as multicast IPv4 addresses. Order matters.
--udp-multicast-iface-v6 <udp_join_multicast_iface_v6>...
[A] Index of network interface for IPv6 multicast. Has to be either not specified or specified the same
number of times as multicast IPv6 addresses. Order matters.
--udp-ttl <udp_ttl> [A] Set IP_TTL, also IP_MULTICAST_TTL if applicable
--protocol <websocket_protocol>
Specify this Sec-WebSocket-Protocol: header when connecting --server-protocol <websocket_reply_protocol>
Force this Sec-WebSocket-Protocol: header when accepting a connection --websocket-version <websocket_version> Override the Sec-WebSocket-Version value
--binary-prefix <ws_binary_prefix>
[A] Prepend specified text to each received WebSocket binary message. Also strip this prefix from outgoing
messages, explicitly marking them as binary even if `--text` is specified
--ws-c-uri <ws_c_uri>
[A] URI to use for ws-c: overlay [default: ws://0.0.0.0/] --ping-interval <ws_ping_interval> Send WebSocket pings each this number of seconds
--ping-timeout <ws_ping_timeout>
Drop WebSocket connection if Pong message not received for this number of seconds --text-prefix <ws_text_prefix>
[A] Prepend specified text to each received WebSocket text message. Also strip this prefix from outgoing
messages, explicitly marking them as text even if `--binary` is specifiedARGS:
<addr1> In simple mode, WebSocket URL to connect. In advanced mode first address (there are many kinds of
addresses) to use. See --help=types for info about address types. If this is an address for
listening, it will try serving multiple connections.
<addr2> In advanced mode, second address to connect. If this is an address for listening, it will accept only
one connection.Basic examples:
Command-line websocket client:
websocat ws://ws.vi-server.org/mirror/
WebSocket server
websocat -s 8080
WebSocket-to-TCP proxy:
websocat --binary ws-l:127.0.0.1:8080 tcp:127.0.0.1:5678
Full list of address types:
ws:// Insecure (ws://) WebSocket client. Argument is host and URL.
wss:// Secure (wss://) WebSocket client. Argument is host and URL.
ws-listen: WebSocket server. Argument is host and port to listen.
inetd-ws: WebSocket inetd server. [A]
l-ws-unix: WebSocket UNIX socket-based server. [A]
l-ws-abstract: WebSocket abstract-namespaced UNIX socket server. [A]
ws-lowlevel-client: [A] Low-level HTTP-independent WebSocket client connection without associated HTTP upgrade.
ws-lowlevel-server: [A] Low-level HTTP-independent WebSocket server connection without associated HTTP upgrade.
wss-listen: Listen for secure WebSocket connections on a TCP port
http: [A] Issue HTTP request, receive a 1xx or 2xx reply, then pass
asyncstdio: [A] Set stdin and stdout to nonblocking mode, then use it as a communication counterpart. UNIX-only.
inetd: Like `asyncstdio:`, but intended for inetd(8) usage. [A]
tcp: Connect to specified TCP host and port. Argument is a socket address.
tcp-listen: Listen TCP port on specified address.
ssl-listen: Listen for SSL connections on a TCP port
sh-c: Start specified command line using `sh -c` (even on Windows)
cmd: Start specified command line using `sh -c` or `cmd /C` (depending on platform)
exec: Execute a program directly (without a subshell), providing array of arguments on Unix [A]
readfile: Synchronously read a file. Argument is a file path.
writefile: Synchronously truncate and write a file.
appendfile: Synchronously append a file.
udp: Send and receive packets to specified UDP socket, from random UDP port
udp-listen: Bind an UDP socket to specified host:port, receive packet
open-async: Open file for read and write and use it like a socket. [A]
open-fd: Use specified file descriptor like a socket. [A]
threadedstdio: [A] Stdin/stdout, spawning a thread (threaded version).
- Read input from console, print to console. Uses threaded implementation even on UNIX unless requested by `--async-stdio` CLI option.
unix: Connect to UNIX socket. Argument is filesystem path. [A]
unix-listen: Listen for connections on a specified UNIX socket [A]
unix-dgram: Send packets to one path, receive from the other. [A]
abstract: Connect to UNIX abstract-namespaced socket. Argument is some string used as address. [A]
abstract-listen: Listen for connections on a specified abstract UNIX socket [A]
abstract-dgram: Send packets to one address, receive from the other. [A]
mirror: Simply copy output to input. No arguments needed.
literalreply: Reply with a specified string for each input packet.
clogged: Do nothing. Don't read or write any bytes. Keep connections in "hung" state. [A]
literal: Output a string, discard input.
assert: Check the input. [A]
assert2: Check the input. [A]
seqpacket: Connect to AF_UNIX SOCK_SEQPACKET socket. Argument is a filesystem path. [A]
seqpacket-listen: Listen for connections on a specified AF_UNIX SOCK_SEQPACKET socket [A]
random: Generate random bytes when being read from, discard written bytes.
Full list of overlays:
ws-upgrade: WebSocket upgrader / raw server. Specify your own protocol instead of usual TCP. [A]
http-request: [A] Issue HTTP request, receive a 1xx or 2xx reply, then pass
http-post-sse: [A] Accept HTTP/1 request. Then, if it is GET,
ssl-connect: Overlay to add TLS encryption atop of existing connection [A]
ssl-accept: Accept an TLS connection using arbitrary backing stream. [A]
reuse-raw: Reuse subspecifier for serving multiple clients: unpredictable mode. [A]
broadcast: Reuse this connection for serving multiple clients, sending replies to all clients.
autoreconnect: Re-establish underlying connection on any error or EOF
ws-c: Low-level WebSocket connector. Argument is a some another address. [A]
msg2line: Line filter: Turns messages from packet stream into lines of byte stream. [A]
line2msg: Line filter: turn lines from byte stream into messages as delimited by '\\n' or '\\0' [A]
foreachmsg: Execute something for each incoming message.
log: Log each buffer as it pass though the underlying connector.
jsonrpc: [A] Turns messages like `abc 1,2` into `{"jsonrpc":"2.0","id":412, "method":"abc", "params":[1,2]}`.
timestamp: [A] Prepend timestamp to each incoming message.
socks5-connect: SOCKS5 proxy client (raw) [A]
socks5-bind: SOCKS5 proxy client (raw, bind command) [A]
exit_on_specific_byte: [A] Turn specific byte into a EOF, allowing user to escape interactive Websocat sessionWhat is websocat command equivalent based on nginx site configuration above? I'm sure websocat can do that since it has many options. Or is there another simple websocket server utilities for that?
| websocat command argument equivalent for this nginx custom configuration? |
/usr/bin/autossh ... -R42301:localhost:8081 [emailprotected] ...-R42301:localhost:8081 - should be -R*:42301:localhost:8081. From the openssh documentation:-R [bind_address:]port:host:hostport
...
By default, TCP listening sockets on the server will be bound to the
loopback interface only. This may be overridden by specifying a
bind_address. An empty bind_address, or the address ‘*’, indicates
that the remote socket should listen on all interfaces. Specifying a
remote bind_address will only succeed if the server's GatewayPorts
option is enabled (see sshd_config(5)). |
I've used autossh (reverse) connecting to my server. The ssh side works like used to. But in an ARM64 system, my Ubuntu has less possibilities but this is another story (...).
So what I see whit nmap the specific port with
127.0.0.1: they are open (and maybe listening)
but when I check the same with my intern IP: 192.168.1.11 then I see they are closed (ifconfig -a to double check my ip - yes).
I have no firewall running, no protection, (ufw also not working), blank iptables, but this makes no sense. Maybe something missing from install? I'm new to this kind of chipsets, so maybe the Ubuntu distro is inefficient and has less support for that.
What I would like to have: I would like also to see the port opened at 192.168...
Maybe there has to be a workaround? with ex. socat? I've tried but got:
socat[4525] E bind(5, {AF=2 0.0.0.0:12001}, 16): Address already in useSo if it is used, why I can't see it from outside (not only on the 127.0.0.1)?
| TCP port visible from inside nor outside |
It's turns out the solution was easier than I expect just adding the -v options logs what it's being sent between the client and the server with to stderr. In my example it will be the following:
socat -v TCP:localhost:8888 pty,rawer &> com.log |
I'm trying to create a bridge between TCP server and a client connected thorough a serial port using socat.
I emulate my TCP server with the following command
socat tcp-listen:8888,reuseaddr -I emulate the serial device with a pty. To create a simple brigde with the following command:
socat -d -d TCP:localhost:8888 pty,rawerThis works fine but, I want to log the contents of the messages between the two devices.
I have tried to do this with the following command:
socat -d -d TCP:localhost:8888 SYSTEM:'tee server.log | socat -d -d - pty | tee client.log' This seems to work fine but my problem is that I get an echo on the server side.
| Socat. Bridge TCP - SERIAL PORT. With log |
The sssd daemon acts as the spider in the web, controlling the login process and more. The login program communicates with the configured pam and nss modules, which in this case are provided by the SSSD package. These modules communicate with the corresponding SSSD responders, which in turn talk to the SSSD Monitor. SSSD looks up the user in the LDAP directory, then contacts the Kerberos KDC for authentication and to aquire tickets.
(PAM and NSS can also talk to LDAP directly using pam_ldap and nss_ldap respectively. However SSSD provides additional functionality.)
Of course, a lot of this depends on how SSSD has been configured; there lots of different scenarios. For example, you can configure SSSD to do authentication directly with LDAP, or authenticate via Kerberos.
The sssd daemon does not actually do much that cannot be done with a system that has been "assembled by hand", but has the advantage that it handles everything in a centralised place. Another important benefit of SSSD is that it caches the credentials, which eases the load on servers and makes it possible to go offline and still login. This way you don't need a local account on the machine for offline authentication.
|
I am basically aware of what these services do separate from each other. What I want to know: what exactly happens on a successful login in a linux based network that uses all of these services? In which order these services are consulted? What service talks to what service?
| PAM vs LDAP vs SSSD vs Kerberos |
Several months after you asked but the correct answer is that you remove all domain information from the group. All the information is set and extracted by SSSD automatically.
The only flaw I see in some of your examples is that you escaped the space with a ^.
An AD group of Enterprise Admins would have a sudoers line that starts with
%Enterprise\ Admins
For example, if your domain is example.com, then the sudoers line looks like
%Enterprise\ [emailprotected] ALL=(ALL) ALL
You can verify this by looking calling getent on the group.
getent group Enterprise\ Admins
|
I'm adding some Fedora 20 workstations to our Windows 2003 domain. I've successfully joined the domain with the boxes, and can login with domain accounts.
Now I'm trying to allow the default AD group Enterprise Admins to use SUDO, however whatever I do, it seems that the group cannot be found (or at least it tells me my user account is not in the sudoers file)
Structure of the OU (default really):mydomain.localBuiltin
Computers
DCOM-Users
DOmain Controllers
ForeignSecurityPrincipals
CompanyNameManagement
Accounting
Admins
SysAccounts
CustomerService
WarehouseUsersI used realmd and sssd to join the domain, and am trying to allow sudo to groups located under the Users OU, but would also like to add some from the CompanyName --> Admins OU/Sub-group as well.
I'm currently trying this with no luck (in /etc/sudoers)
%MYDOMAIN\\Enterprise^Admins ALL=(ALL) ALLI've also tried variations as well, such as:
%MYDOMAIN\\Users\Enterprise^Admins ALL=(ALL) ALL
%Enterprise^[emailprotected] ALL=(ALL) ALLetc... nothing seems to be working. Even after reboots, and/or systemctrl restart sssd.
If i explicitly add my domain account to the /etc/sudoers file, it works no problem.
[emailprotected] ALL=(ALL) ALLThere are a few resources that seem to indicate it should be possible to add AD groups to sudoers, however so far none of them have worked for me:
http://funwithlinux.net/2013/09/join-fedora-19-to-active-directory-domain-realmd/
https://serverfault.com/questions/387950/how-to-map-ad-domain-admins-group-to-ubuntu-admins
https://help.ubuntu.com/community/LikewiseOpen
| Allow AD Groups to SUDO |
This is actually shockingly easy. If your nsswitch is files ldap; just add an entry for them in /etc/passwd and modify whatever parameter you want. If they don't already exist in /etc/passwd, you could do getent passwd <username> | sed 's|/home/<username>|/home/remoteusers/<username>|g' >> /etc/passwd for instance to change their home directory from the root of /home to a subfolder of home called remoteusers. The caveat is that you cannot use useradd or usermod, you must edit the file with an editor.
|
I have an LDAP user who accesses a server based on having the appropriate LDAP host attribute via sssd. This user does not show up in /etc/passwd because he is not local. How do I modify his home dir location if he has already logged in and it was created in the default location? RHEL 6 Is it just usermod -d /new/location -m?
| Edit home directory for an LDAP user in Linux |
So, how do I clear a user's cached Active Directory password on CentOS 7?Generally sss_cache should be the right way to tell sssd to re-retrieve objects it has probably already cached. But afaik sssd does indeed use the cached objects again if nothing could be retrieved from the AD.
You should always be able to reset cached credentials by setting
[domain/your-domain.tld]
...
cache_credentials = Falsein the /etc/sssd/sssd.conf, restarting the sssd service and reauthenticating with your user. This way you should be able to determine if authentication over SSSD/AD works at all. To check if the complete setup is working with the current settings (without using any caches), it's always a good thing to actually delete all caches. See the info at the bottom for how to do that most effectively.Is there a way for a "regular" user to do that themselves (in case we wanted to roll this out to other systems)?I don't know how this could be safely implemented. Imho this is nothing what you want. But it shouldn't be necessary anyway. SSSD should always re-evaluate his cached credentials based on some conditions.
Most of the time it's a good idea to set the following to force re-evaluation after some days and to actually notice if something with environment is going wrong
[pam]
...
offline_credentials_expirationas per default offline_credentials_expiration is set to 0 (No limit)Most of the time when i want to be sure, there are no more caches in use, i do the following
systemctl stop sssd
rm /var/lib/sssd/db/*
systemctl start sssdThis can lead to a non-working sssd setup (but only if something is wrong with its setup, as all data sssd holds are simply re-retrievable from the AD).
|
I built a CentOS 7 install on my company laptop and configured it to authenticate to the company AD servers like so:Install packages:
yum install sssd realmd oddjob oddjob-mkhomedir adcli samba-common samba-common-tools krb5-workstation openldap-clients policycoreutils-pythonAdd AD servers to /etc/hosts.
Join realm:
realm join --user=tech adserver.example.com
realm permit -g activedirectorygroup@domainChange use_fully_qualified_names to False and fallback_homedir to /home/%u in /etc/sssd/sssd.conf.
Restart daemons:
systemctl restart sssd && systemctl daemon-reloadSetup ITGROUP to be able to use sudo:
echo "%ITGROUP ALL=(ALL) ALL" > /etc/sudoers.d/ITGROUPEverything has been working fine. ...until I changed my password on my Windows 10 PC. In fact, the CentOS box is letting me, but just with the old password. I've done a bunch of Googling and tried a bunch of things (e.g., sss_cache -E, kdestroy -A), but I can't seem to flush the cache so I can use my new password.
So, how do I clear a user's cached Active Directory password on CentOS 7? Is there a way for a "regular" user to do that themselves (in case we wanted to roll this out to other systems)?
Update:
I tried some of the suggestions, but the laptop wouldn't forget the old credentials. I ended up removing the PC from the realm and re-adding it. I did add this to my sssd.conf:
[sssd]
...
account_cache_expiration = 2
cached_auth_timeout = 3600
refresh_expired_interval = 4050[pam]
reconnection_retries = 3
offline_credentials_expiration = 2The login seems to be caching the AD stuff, but it tells me Authenticated with cached credentials, your cached password will expire at: now when I login or sudo. I'm hoping that next time my password expires and I change it, this system will recognize it. FYI, my whole config is:
[sssd]
domains = adserver.example.com
config_file_version = 2
services = nss, pam[domain/adserver.example.com]
ad_domain = adserver.example.com
krb5_realm = adserver.example.com
realmd_tags = manages-system joined-with-samba
cache_credentials = True
id_provider = ad
krb5_store_password_if_offline = True
default_shell = /bin/bash
ldap_id_mapping = True
use_fully_qualified_names = False
fallback_homedir = /home/%u
access_provider = simple
simple_allow_groups = [emailprotected]
account_cache_expiration = 2
cached_auth_timeout = 3600
refresh_expired_interval = 4050[pam]
reconnection_retries = 3
offline_credentials_expiration = 2Update #2:
I've been using this configuration for quite some time now. I've increased the account_cache_expiration and offline_credentials_expiration from 2 to 4, but it's been working so well we've begun using this setup on our servers.
| How do I clear a user's cached Active Directory password on CentOS 7? |
This was enabled in sssd 1.9.5, by setting sssd.conf to include:
ldap_rfc2307_fallback_to_local_users = truehttps://fedorahosted.org/sssd/wiki/Releases/Notes-1.9.5
|
Our LDAP server is running RFC 2307 groups (memberuid contains a username, not a DN). With our old nscd/nss_ldap/pam_ldap setup, you could list a non-LDAP user (a system user from /etc/passwd) in an LDAP group's memberuid attribute, and that system user will be a member of the group.
However, on machines I've upgraded to SSSD, this no longer works: SSSD just strips out the non-LDAP user from the member list.
I've confirmed this behavior by logging in as the user and using id and also by running getent group group.
Here is my sssd.conf (with some details redacted and clearly marked as such)
[sssd]
config_file_version = 2
services = nss, pam
domains = REDACTED.net[nss]
# defaults are OK[pam]
# defaults are OK[domain/REDACTED.net]
enumerate = true
id_provider = ldap
auth_provider = ldap
access_provider = ldap
chpass_provider = ldapldap_uri = _srv_
ldap_chpass_uri = ldap://haruhi.REDACTED.net
ldap_search_base = dc=REDACTED,dc=net?subtree?
ldap_schema = rfc2307
ldap_tls_cacert = /usr/local/share/ca-certificates/REDACTED-CA.crt
ldap_id_use_start_tls = true
ldap_pwd_policy = shadowldap_access_filter = memberOf=cn=UNIX Users,ou=Policies,dc=REDACTED,dc=net
ldap_access_order = filter, authorized_service, hostldap_default_bind_dn = uid=haruhi,ou=Machines,dc=REDACTED,dc=net
ldap_default_authtok = VERY_REDACTED/etc/nsswitch.conf has boring entries for passwd/group/shadow:
passwd: compat ldap sss
group: compat ldap sss
shadow: compat sss(ldap is still in there, but it isn't actually installed on the system any more)
Also, I doubt it matters (as I see the same behavior on other machines) but this machine—Haruhi—is also the master LDAP server, running OpenLDAP.
How do I configure SSSD to not strip out system users from LDAP groups?
| Adding a system user to an LDAP group with SSSD |
I would look at few things
- is oddjobd running?
- any messages related to this or PAM in authlog, messages
- is SElinux enabled or enforced? check audit log for any AVC denial messagesLooking again at your sssd.conf, you may want to move override_homedir into the DOMAIN section, otherwise sssd seems to get home directory information from ldap.
|
I currently have a server which has Kerberos/SSSD/Samba to authenticate to Windows 2012 AD.
In /etc/pam.d/system-auth oddjob_mkhomedir is set as below:
session optional pam_oddjob_mkhomedir.so umask=0077 skel=/etc/skelThis was set by running authconfig --enablesssdauth --enablesssd --enablemkhomedir --update.
However when logging in via SSH with an AD account the home directory isn't created and the user simply ends up in root with /bin/sh rather than /bin/bash.
Nothing in the error logs suggests either sssd isn't running as expected or the PAM module isn't being called.
Configs copied below:
/etc/ssh/ssh_config
Port 22
ListenAddress x.x.x.x
Protocol 2
SyslogFacility AUTHPRIV
PermitRootLogin yes
PasswordAuthentication yes
ChallengeResponseAuthentication no
KerberosAuthentication yes
GSSAPIAuthentication yes
GSSAPICleanupCredentials yes
UsePAM yes
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
X11Forwarding yes
Subsystem sftp /usr/libexec/openssh/sftp-server/etc/sssd/sssd.conf
[sssd]
config_file_version = 2
debug_level = 7
domains = mydomain.co.uk
services = nss, pamoverride_homedir = /home/%d/%u
default_shell = /bin/bash[nss][pam][domain/mydomain.co.uk]
id_provider = ad
access_provider = ad
cache_credentials = true
debug_level = 7 | oddjob_mkhomedir doesn't run when logging in via SSH with Kerberos |
Thanks to the sssd maintainers I found the answer. Here's a working config which does what I needed, i.e. allow SSH tunneling but not SSH login to the AD users which are members of the AD LimitedGroup.
Note that a member of the limited group must ssh as user@MYDOMAIN_TEST.GLOBAL, not as [emailprotected], or it won't work.
The gist of the solution is in using the SSSD section domain name instead of the AD domain name in the simple_allow_groups directive. Note, however, that the config also works without the lines access_provider = simple and simple_allow_groups = .... It is also possible to set simple_allow_groups = group without the use_fully_qualified_names = True directive, as reported by an user in the comments.
Also, note that this config uses ldap_user_search_base instead of the deprecated ldap_user_search_filter.
The other configuration options are only for completeness as they were already in the config file.
[sssd]
domains = MYDOMAIN.GLOBAL,MYDOMAIN_TEST.GLOBAL
config_file_version = 2
services = nss, pam[nss]
default_shell = /bin/bash[domain/MYDOMAIN_TEST.GLOBAL]
ldap_user_search_base = DC=MYDOMAIN,DC=GLOBAL?subtree?(memberOf=CN=LimitedGroup,OU=Groups,DC=MYDOMAIN,DC=GLOBAL)
default_shell = /sbin/nologin
ad_server = ad.mydomain.global
ad_backup_server = ad2.mydomain.global
ad_domain = MYDOMAIN.GLOBAL
krb5_realm = MYDOMAIN.GLOBAL
realmd_tags = manages-system joined-with-adcli
cache_credentials = False
id_provider = ad
krb5_store_password_if_offline = True
ldap_id_mapping = True
use_fully_qualified_names = True
fallback_homedir = /home/%u@%d
access_provider = simple
simple_allow_groups = LimitedGroup@MYDOMAIN_TEST.GLOBAL[domain/MYDOMAIN.GLOBAL]
ldap_user_search_base = DC=MYDOMAIN,DC=GLOBAL?subtree?(memberOf=CN=AdminsGroup,OU=Groups,DC=MYDOMAIN,DC=GLOBAL)
default_shell = /bin/bash
ad_server = ad.mydomain.global
ad_backup_server = ad2.mydomain.global
ad_domain = MYDOMAIN.GLOBAL
krb5_realm = MYDOMAIN.GLOBAL
realmd_tags = manages-system joined-with-adcli
cache_credentials = False
id_provider = ad
krb5_store_password_if_offline = True
ldap_id_mapping = True
use_fully_qualified_names = True
fallback_homedir = /home/%u@%d
access_provider = simple
simple_allow_groups = [emailprotected] |
I'm trying to define different login shells for different users of an AD domain, as described here. The aim is to deny members of a particular group from logging in while allowing them to do SSH tunneling.
Here below is the file /etc/sssd/sssd.conf. MYDOMAIN.GLOBAL is the default domain provided by the AD. The config below defines a test domain MYDOMAIN_TEST.GLOBAL, which is not in the AD, as the domain for these limited users. (This is just a configuration for testing: later, in the MYDOMAIN_TEST.GLOBAL domain section, override_shell = /bin/zsh will be replaced by override_shell = /sbin/nologin.)
[sssd]
domains = MYDOMAIN.GLOBAL,MYDOMAIN_TEST.GLOBAL
config_file_version = 2
services = nss, pam[nss]
default_shell = /bin/bash[domain/MYDOMAIN.GLOBAL]
ad_server = ad.mydomain.global
ad_domain = MYDOMAIN.GLOBAL
ldap_user_search_filter = (memberOf=CN=AdminsGroup,OU=Groups,DC=MYDOMAIN,DC=GLOBAL)
id_provider = ad
simple_allow_groups = [emailprotected]
override_shell = /bin/bash[domain/MYDOMAIN_TEST.GLOBAL]
ad_server = ad.mydomain.global
ad_domain = MYDOMAIN.GLOBAL
ldap_user_search_filter = (memberOf=CN=LimitedGroup,OU=Groups,DC=MYDOMAIN,DC=GLOBAL)
id_provider = ad
simple_allow_groups = [emailprotected]
override_shell = /bin/zshA member of MYDOMAIN.GLOBAL is able to login via SSH, while a member of MYDOMAIN_TEST.GLOBAL can't and gets a "Permission denied, please try again" or a "Authentication failed" error.
The sssd logfiles don't show any error.
Why is that?
Does MYDOMAIN_TEST.GLOBAL need to be present in the AD? If yes, is it possible to somehow bypass this and configure sss with different "local categories" of users to do what I want?
(Note: Apparently this can be done with nlscd, as per this question and this other question, but it requires a LDAP server, and configuring it to use an AD is another can of worms.)
| Setting login shell in SSS configuration for users from Active Directory |
Finally I followed these instructions and suddenly it started working, its weird I still dont understand fully what was wrong:
Manually Connecting an SSSD Client to an Active Directory Domain
https://access.redhat.com/articles/3023951 .
I can now do id and su for an ActiveDir user on Centos7 like $ su [emailprotected] with ActiveDir password and login. Bottomline the /etc/hosts , /etc/krb5.conf, /etc/resolv.conf , /etc/sssd/sssd.conf, /etc/samba/smb.conf need to be carefully checked as all kinds of errors can happen.
|
When I try to do a su [emailprotected] I get a "user does not exist" message.
[emailprotected] exists in Active Directory. I can do kinit [emailprotected] successfully and get a ticket. Here are the steps I did:I have MIT KDC on CentOS 7 CENTOSREALM.COM and Active Directory realm ADREALM.COM
On CentOS I did realm join ADREALM.COM which gave "* Successfully enrolled machine in realm". I can see the centos hostname in Active Directory Computers container.
But I cannot login to the CentOS server with [emailprotected] this user exists in AD. Where do I look for errors or steps to debug this issue?
The sssd.conf content:
[sssd]
domains = adrealm.com
config_file_version = 2
services = nss, pam[domain/adrealm.com]
ad_server = adrealm.com
ad_domain = adrealm.com
krb5_realm = ADREALM.COM
realmd_tags = manages-system joined-with-adcli
cache_credentials = True
id_provider = ad
krb5_store_password_if_offline = True
default_shell = /bin/bash
ldap_id_mapping = True
use_fully_qualified_names = True
fallback_homedir = /home/%u@%d
access_provider = ad
debug_level = 3 | sssd and Active Directory user does not exist in CentOS |
The option that controls this behavior is buried in sssd.conf(5) on CentOS 7 and Fedora, but not in the online man page.
sssd.conf
[sssd]
enable_files_domain = falseReference 3 shows that sssd makes a "fast cache for local users."
From man sssd.conf(5) on my Fedora system: enable_files_domain (boolean)
When this option is enabled, SSSD prepends an implicit domain with
“id_provider=files” before any explicitly configured domains. Default: trueDisabling this behavior lets me make a simple check to see if it is a local user or domain user.
Referencesddg: sssd disable caching local users
https://bugzilla.redhat.com/show_bug.cgi?id=1357418
https://fedoraproject.org/wiki/Changes/SSSDCacheForLocalUsers
Fedora 27 sssd.conf(5)
https://bgstack15.wordpress.com/2018/02/23/getent-passwd-s-sss-localuser-shows-local-user/ |
tl;dr
I want to easily and quickly tell if a user is local or domain (don't care which domain).
Environmentfreeipa-client-4.6.1-3.fc27.x86_64
sssd-1.16.0-4.fc27.x86_64Full story
I am writing a userinfo.sh script that will show if a user is local, sssd, can ssh, and is permitted by sssd.
Currently I am doing the check for if the user is from the domain with the getent passwd -s sss $USERNAME command. But I ran into an issue where checking the sssd database returns a local user!
# getent passwd -s sss 'bgstack15-local'
bgstack15-local:x:1000:1000:bgstack15-local:/home/bgstack15-local:/bin/bashChecking the contents of the database (cache) for sss shows sssd apparently caches all sorts of information about the local user.
# sudo su root -c 'strings /var/lib/sss/db/* | grep bgstack15-local' | sort | uniq
name=bgstack15-local@implicit_files,cn=groups,cn=ih
name=bgstack15-local@implicit_files,cn=groups,cn=implicit_files,cn=sysdb
name=bgstack15-local@implicit_files,cn=users,cn=implicit_files,cn=sysdb
[...output truncated]I tried clearing the sssd cache overall, and just for the user. Neither made a difference.
# sss_cache -U
# sss_cache -u bgstack15-localThe user does show up as a local user, and I promise it is only a local user!
getent passwd -s files 'bgstack15-local'
bgstack15-local:x:1000:1000:bgstack15-local:/home/bgstack15-local:/bin/bashThe man pages for getent(1) and getpwent(3) don't help me understand what could be going on. sssd(8) shows me that sssd can cache local users, which actually goes against what I want! The nss section of sssd.conf(5) doesn't help, but maybe I didn't take enough time to read it. I'm a little stuck.
My sssd.conf
[domain/ipa.example.com]
id_provider = ipa
ipa_server = _srv_, dns1.ipa.example.com
ipa_domain = ipa.example.com
ipa_hostname = fc27c-01a.ipa.example.com
auth_provider = ipa
chpass_provider = ipa
access_provider = ipa
cache_credentials = True
ldap_tls_cacert = /etc/ipa/ca.crt
krb5_store_password_if_offline = True
[sssd]
services = nss, pam, ssh, sudo
domains = ipa.example.com
[nss]
homedir_substring = /home
[pam]
[sudo]
[autofs]
[ssh]
[pac]
[ifp]
[secrets]
[session_recording]Last resort
I can try doing my checks against ${USERNAME}@${DOMAIN} when doing the -s sss check, but that means I then have to iterate over all domains in sssd.conf and that would slow the process down.
| getent passwd -s sss LOCALUSER shows local user |
Store the files in the skeleton directory. When a new user is created, the files in that directory should be copied to their home directory.
The directory is normally /etc/skel.
|
I have a network with several RHEL6 workstations and RHEL IdM Server (a.k.a. FreeIPA) as a domain controller. Every LDAP user can log into the every workstation. When the user is logging in for the first time, SSSD creates $HOME/$USER directory for them.
I would like to set customized Gnome configuration for each user with this command:nautilus-actions-new --label="Shred" --tooltip="Purge file" --icon="gtk-dialog-warning" --toolbar-label="Shred" --command="shred" --parameters="-f -u -v -z %f" -gAs I know, Gnome settings are stored locally in the homedir of each user and there is no possibility to set them globally for every user. So I wonder are there any hooks to SSSD's new homedir creating event in order to run the mentioned command?
| How to run script when SSSD creates home directory for a new user |
Sadly there doesn't seem to be an option to add custom configuration parameters to the sssd.conf file generated by realmd.
I had to adjust the generated config to contain my needed settings after joining the domain with realm join and restart sssd (service restart sssd) for the settings to take effect.
|
I'm trying to join a Ubuntu 16.04 to a Windows domain (active directory) using realmd + sssd. Basically I was following this post which worked pretty well and I was able to join my server and could successfully authenticate as AD user. However there are two pieces missing in the integration:Register server's hostname in DNS
Use sssd-sudo for user authorizationRegister server's hostname in DNS
As mentioned I successfully join the AD by using
realm join --user=dpr MYDOMAIN.INT --install=/:
root@ip-172-28-5-174 ~ # realm list
mydomain.int
type: kerberos
realm-name: MYDOMAIN.INT
domain-name: mydomain.int
configured: kerberos-member
server-software: active-directory
client-software: sssd
required-package: sssd-tools
required-package: sssd
required-package: libnss-sss
required-package: libpam-sss
required-package: adcli
required-package: samba-common-bin
login-formats: %[emailprotected]
login-policy: allow-realm-loginsHowever, dispite the successful join, my server is not known to the other machines in the domain using its hostname ip-172-28-5-174.mydomain.int. I found this documentation that mentions a dyndns_update setting in the sssd.conf file.
As I'm using realm. The sssd configuration is generated automatically by issuing the join command. The generated config file looks like this:
[sssd]
domains = mydomain.int
config_file_version = 2
services = nss, pam[domain/mydomain.int]
ad_domain = mydomain.int
krb5_realm = MYDOMAIN.INT
realmd_tags = manages-system joined-with-adcli
cache_credentials = True
id_provider = ad
krb5_store_password_if_offline = True
default_shell = /bin/bash
ldap_id_mapping = True
use_fully_qualified_names = True
fallback_homedir = /home/%u@%d
access_provider = adThat is I somehow need to add dyndns_update = True to this generated file. But how?
Use sssd-sudo for user authorization
Additionally I want to make sssd to read my sudo configuration from AD. I think this can be achieved using sssd-sudo but this needs to be enabled/configured in the sssd.conf file as well by adding sudo to the sssd services and use sudo_provider = ldap for my domain. Again I'm not able to figure out how to do this with realm.
Basically I want my generated config file to look like this:
[sssd]
domains = mydomain.int
config_file_version = 2
services = nss, pam, sudo[domain/mydomain.int]
id_provider = ad
access_provider = ad
sudo_provider = ldap
ad_domain = mydomain.int
krb5_realm = MYDOMAIN.INT
realmd_tags = manages-system joined-with-adcli
cache_credentials = True
krb5_store_password_if_offline = True
default_shell = /bin/bash
ldap_id_mapping = True
use_fully_qualified_names = True
fallback_homedir = /home/%u@%dAny ideas on how this can be achieved?
| Configure SSSD (sudo and dyndns_update) with realmd |
Looks like a bug in Fedora's SELinux policy.
Before the fix is released, you can use audit2allow generated policy or the policy in the bug report to allow access.
|
System:HP Pavilion Power Laptop 15-cb0xx
Intel i7-7700HQ w/ integrated graphics enabled (can't be turned off in bios)
Fedora 28
NVIDIA GTX 1050 (mobile)I used the dnfdragora GUI to update about 119 packages (I forgot to update for a while :/). At some point I got a notification from SELinux:
SELinux is preventing sss_cache from write access on the directory /var/lib/sss/db/I dug through /var/log/messages and /var/log/audit/audit.log and found the same stuff that SELinux told me.
After all this went down, I noticed things were going kind of slowly, so I rebooted. The reboot was slower, particularly obvious when the Fedora logo was loading, when the login GUI was loading, and when the desktop was loading. An additional reboot did not fix anything.
From looking at the manpage for sss_cache I get the gist of what it does, and that it works with the System Security Services Daemon (SSSD).
This is what the SELinux dialog box is telling me:I understand that this will notify the maintainers of a potential bug, and the policy changes will prevent SELinux from alerting on sss_cache in the future. I do not know anything about SELinux other than it provides added/configurable security additions to a Linux system. However, I still do not understand why this happened, or if there are other, potentially better, solutions. Nor is it clear to me if this will clear up the slowdown issues I noticed.
Can anyone tell me:Why this might have happened? I can guess that SELinux considers anything associated with SSSD as very important to protect, but why is it not aware of a utility meant to work with SSSD?
Should I just report the bug and create the local policy module, or something else?
Should I undo the transaction that led to all this and update the packages in smaller groups? Would it even undo the problem?
Could this have caused the slowdown issues I noted above? I know from working with VMs (specifically expanding storage space in VirtualBox) that leaving an old entry /etc/fstab can slow down boot because the system is looking for something that doesn't exist. Is something similar going on here?I am loath to just do what the words on the screen say without additional information. I don't want to put a band-aid on a bomb crater without realizing it.
(Additional Information as Requested):
I should have stated: /var/lib/sss/db/ is a directory.
ls -Z /var/lib/sss/ output for db/: system_u:object_r:sssd_var_lib_t:s0
Excerpt from audit.log (includes a potentially unrelated line sandwiched between two relevant ones):
type=AVC msg=audit(1543865969.237:241): avc: denied { write } for pid=18065 comm="sss_cache" name="db" dev="sdb2" ino=787765 scontext=system_u:system_r:groupadd_t:s0 tcontext=system_u:object_r:sssd_var_lib_t:s0 tclass=dir permissive=0
type=GRP_MGMT msg=audit(1543865969.239:242): pid=18062 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:groupadd_t:s0 msg='op=modify-group acct="rpcuser" exe="/usr/sbin/groupmod" hostname=? addr=? terminal=? res=success'
type=AVC msg=audit(1543865969.264:243): avc: denied { write } for pid=18067 comm="sss_cache" name="db" dev="sdb2" ino=787765 scontext=system_u:system_r:groupadd_t:s0 tcontext=system_u:object_r:sssd_var_lib_t:s0 tclass=dir permissive=0Output of ls -Z /usr/sbin/sss_cache (location found via which sss_cache):
system_u:object_r:bin_t:s0Turns out the "details" window had a lot of info: | SELinux Interfering With sss_cache |
First, only the management console was removed from WS2016, but the UNIX schema is still there, I think it should still be accessible with e.g. ADSI edit. So you can still use the POSIX attributes, it's just harder to set them.
Second, the automatic ID mapping currently doesn't allow you to select any ranges manually. We're working on that upstream, but it won't be ready anytime soon and even then, you're probably not after setting a range, but rather setting the same mapping as you had before, 1:1.
So if you're going with the automatic ID mapping, you'd have to either chown the files or create per-machine overrides using the sss_override command line tool.
|
I have a setup with RHEL 7.4 machines that connect to Active Directory (AD) running on a Windows Server 2016 Datacenter Edition. The Linux machines are in direct integration with the AD.
Since Identity Management for Unix (IDMU) & NIS Server Role is removed from this version of Windows, the solution is to use sssd to autogenerate UID and GID numbers.
I am not able to understand how the autogenerated GID will be mapped to the actual group on the Linux machine.
For example, if user john is a member of LinuxGroup in the AD and is logged in and that should be mapped to group localgrp on the Linux machine, how will this work out? How would he get linuxgrp privileges if the autogenerated GID is 500 but localgrp GID is 10 on the Linux machine?
To have only central management of users, we are not allowed to add users directly in Linux i.e. in /etc/passwd.
Thanks.
| Mapping AD groups to Linux groups - sssd and Windows server 2016 |
The problem seems to have been that my admin had created an entry on the Domain Controller for this server. This apparently caused a conflict that caused Kerberos to encounter the following error when trying to join:
kyle@Server21:~$ sudo net ads join -k
Failed to join domain: failed to lookup DC info for domain 'COMPANYNAME.LOCAL' over rpc: An internal error occurred.I'm not sure that this error was entirely accurate since my admin said the server was joined to the domain on his end and realmd indicated that I was joined as well:
kyle@Server21:~$ realm join COMPANYNAME.LOCAL
realm: Already joined to this domainThe steps I followed to get a successful Kerberos join were as follows:Admin removed the entry in the Domain Controller
Reran Kerberos configuration using: sudo dpkg-reconfigure krb5-config
Chose the options in the configuration to add the Domain Controller explicitly to the [realms] section of krb5.conf
Changed the hostname to ensure a new record was created
Pulled a new ticket using kinit
Joined the domain using sudo net ads join -k Final result:
kyle@SERV21:~$ sudo net ads join -k
Using short domain name -- COMPANYNAME
Joined 'SERV21' to dns domain 'CompanyName.Local' |
I'm trying to join an Ubuntu 14.04 server to a Windows 2003 R2 domain. My admin says that from the controller side, it is part of the domain. But SSSD can't seem to start and DNS update fails.
I've been following a variety of guides to try and get this working but have been unsuccessful in completing any one of them without errors.
Ubuntu Server Guide
KiloRoot
NetNerds
Fedora SSSD Guide
Discovery seems to be working just fine:
kyle@Server21:~$ realm discover COMPANYNAME.LOCAL
CompanyName.Local
type: kerberos
realm-name: COMPANYNAME.LOCAL
domain-name: companyname.local
configured: kerberos-member
server-software: active-directory
client-software: sssd
required-package: sssd-tools
required-package: sssd
required-package: libnss-sss
required-package: libpam-sss
required-package: adcli
required-package: samba-common-bin
login-formats: %U
login-policy: allow-realm-logins
companyname.local
type: kerberos
realm-name: COMPANYNAME.LOCAL
domain-name: companyname.local
configured: norealmd says that I'm joined to the domain as well:
kyle@Server21:~$ realm join COMPANYNAME.LOCAL
realm: Already joined to this domainKerberos took my admin's authentication:
kyle@Server21:~$ kinit -V administrator
Using default cache: /tmp/krb5cc_0
Using principal: [emailprotected]
Password for [emailprotected]:
Authenticated to Kerberos v5But when it comes time to join, the DNS Update fails:
kyle@Server21:~$ sudo net ads join -k
Using short domain name -- COMPANYNAME
Joined 'SERVER21' to dns domain 'CompanyName.Local'
No DNS domain configured for server21. Unable to perform DNS Update.
DNS update failed: NT_STATUS_INVALID_PARAMETERAnd SSSD is still having an issue starting:
kyle@Server21:~$ systemctl status sssd.service
● sssd.service - System Security Services Daemon
Loaded: loaded (/lib/systemd/system/sssd.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Wed 2016-06-22 09:57:57 EDT; 37min ago
Process: 16027 ExecStart=/usr/sbin/sssd -D -f (code=exited, status=1/FAILURE)Jun 22 09:57:55 Server21 sssd[16038]: Starting up
Jun 22 09:57:55 Server21 sssd[16041]: Starting up
Jun 22 09:57:55 Server21 sssd[16042]: Starting up
Jun 22 09:57:56 Server21 sssd[be[16043]: Starting up
Jun 22 09:57:57 Server21 sssd[be[16043]: Failed to read keytab [default]: No such file or directory
Jun 22 09:57:57 Server21 sssd[16031]: Exiting the SSSD. Could not restart critical service [COMPANYNAME.LOCAL].
Jun 22 09:57:57 Server21 systemd[1]: sssd.service: Control process exited, code=exited status=1
Jun 22 09:57:57 Server21 systemd[1]: Failed to start System Security Services Daemon.
Jun 22 09:57:57 Server21 systemd[1]: sssd.service: Unit entered failed state.
Jun 22 09:57:57 Server21 systemd[1]: sssd.service: Failed with result 'exit-code'.The only part of krb5.conf that is specific to me is the [libdefaults]:
kyle@Server21:~$ cat /etc/krb5.conf
[libdefaults]
default_realm = COMAPNYNAME.LOCALThough on a previous install I thought there was something else in [realms] but I can't remember what. The Fedora guide talks about adding something there when DNS lookups aren't working but doesn't go into enough detail for me to figure out exactly what is supposed to be there.
My modifications to the smb.conf:
[global]## Browsing/Identification #### Change this to the workgroup/NT-domain name your Samba server will part of
workgroup = COMPANYNAME
client signing = yes
client use spnego = yes
kerberos method = secrets and keytab
realm = COMPANYNAME.LOCAL
security = adsMy sssd.conf
kyle@Server21:~$ sudo cat /etc/sssd/sssd.conf
[sssd]
services = nss, pam
config_file_version = 2
domains = COMPANYNAME.LOCAL[domain/COMPANYNAME.LOCAL]
id_provider = ad
access_provider = ad
override_homedir = /home/%d/%uAnd since the Ubuntu guide says that ownership and permissions are important:
kyle@Server21:~$ sudo ls -la /etc/sssd
total 12
drwx--x--x 2 sssd sssd 4096 Jun 21 14:34 .
drwxr-xr-x 103 root root 4096 Jun 22 10:21 ..
-rw------- 1 root root 172 Jun 21 14:22 sssd.confThe Ubuntu guide also mentions that the hosts file could cause issues with the DNS updating but I think I've followed their example correctly:
kyle@Server21:~$ cat /etc/hosts
127.0.0.1 localhost
127.0.1.1 Server21
192.168.XXX.XXX Server21 Server21.COMPANYNAME.LOCAL# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allroutersSo where am I going wrong here? The domain controller says it is part of the domain. I have Apache and OpenSSH both up and accessible. But there is a lot more this server is going to do and so I want to make sure everything is configured properly before moving forward.Edit:
I changed my hosts file based on advice from this page so that it looks like this now:
kyle@Server21:~$ cat /etc/hosts
127.0.0.1 localhost
127.0.1.1 Server21.COMPANYNAME.LOCAL Server21
192.168.11.11 Server21.COMPANYNAME.LOCAL Server21# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allroutersNow getent returns:
kyle@Server21:~$ sudo getent hosts Server21
127.0.1.1 Server21.COMPANYNAME.LOCAL Server21 Server21
192.168.11.11 Server21.COMPANYNAME.LOCAL Server21 Server21And net ads join now has a different error message:
kyle@Server21:~$ sudo net ads join -k
Failed to join domain: failed to lookup DC info for domain 'COMPANYNAME.LOCAL' over rpc: An internal error occurred.So far the only advice I've found on this error says to make sure that the AD server is in resolv.conf and it's IP is the only entry.
kyle@Server21:~$ cat /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 192.168.XXX.XXXTo answer a comment:
kyle@Server21:~$ nslookup -type=SRV _ldap._tcp.companyname.local
Server: 192.168.XXX.XXX
Address: 192.168.XXX.XXX#53_ldap._tcp.companyname.local service = 0 100 389 companynamedc.companyname.local.Somewhere along the way SSSD was able to start and is now active. Though I'm unsure of what I've done that fixed it.
| Trouble Joining an Active Directory Domain |
The solution was to extend the id map range visible in ldap ldap, our ad is very large and it looks like the default range was not big enough to cover all the users in the range, which means that it would only be able to convert the objectSID which it could see. My SID was way above my colleagues, which is why he was able to login but I was not.
The solution was to add the following to the main part of the SSSD.confldap_idmap_default_domain_sid = SID OF THE DOMAIN
ldap_idmap_range_min = 200000
ldap_idmap_range_max = 2000200000
ldap_idmap_range_size = 1000000Ref:
https://lists.fedorahosted.org/archives/list/[emailprotected]/thread/2YYG6LPUYWX2TUTD5SY5NNTHOTQQIJTD/
|
I have been trying to nail down the process of binding a Centos 7 install to a Windows domain but am struggling. I have managed to successfully do this in the past on a couple of boxes but I am now trying to document the process and it's doing very strange things.
I have managed to perform the bind using the following process:Install and configure ntp
Install packages: realmd, oddjob, oddjob-mkhomedir, sssd, samba-common, krb5-workstation, adcli
Create a Kerberos ticket: kinit [emailprotected]
realm join
modify sssd config[sssd]
domains = my.domain
config_file_version = 2
services = nss, pam[domain/my.domain]
ad_domain = my.domain
krb5_realm = MY.DOMAIN
realmd_tags = manages-system joined-with-adcli
cache_credentials = True
id_provider = ad
krb5_store_password_if_offline = True
default_shell = /bin/bash
ldap_id_mapping = True
use_fully_qualified_names = false
fallback_homedir = /home/%u@%d
access_provider = ad
override_homedir = /home/%u
override_shell = /bin/bashrestart sssd serviceThis has worked in the past but for some reason I was not able to login using my network credentials, however my colleague was able to log in successfully using only one of his accounts.
When we added debug to the sssd config the log file displayed the error:
Could not convert objectSID [MY AD SID HERE] to a UNIX IDIt also picked out my actual account name from AD so it is definitely pull information. We have the same rights on the system and it just doesn't make sense.
Any suggestions on what else I could try?
| SSSD Centos 7 AD Binding - only some users are able to login |
Put those users into a group, then use a pam_access rule in /etc/security/access.conf to only allow logins if the user is in that group (and also for root, any sysadmins, and monitoring, if necessary) e.g.
+ : root wheel nagios : ALL
+ : yourusergrouphere : ALL
- : ALL : ALL |
I am trying to set up a couple of Linux workstations (RedHat 7), and I am trying to figure out how to set up authentication against an LDAP server with some unusual requirements.
I basically know how to set up LDAP authentication using sssd, but I don't know how to restrict authentication to only certain users to meet my requirement.
To enable LDAP configuration, I would use this command line:
authconfig --enableldap --enableldapauth --ldapserver="<redacted>" --ldapbasedn="<redacted>" --update --enablemkhomedirThis will allow all LDAP users to log on, and as far as I know works just fine. However, my requirement is that only some users from LDAP can log in, and the list of users will be supplied in a separate text file (by user login name).
More information: We have an LDAP server (Active Directory, actually) with a couple thousand users. Only about 20 of them who have a need to work on these workstations should be allowed to log on to these workstation. Unfortunately, LDAP does not include any information related to this, and I do not have control of the LDAP server. Instead, every couple of weeks, I get a text file with a list of the user names who should be allowed to log on.
How can I set up authentication to use LDAP for user name/password/user ID etc. while also restricting it to only users on this list?
| Using openldap authentication only for some users |
I have found some help on the #sssd IRC channel.
Apparently the user is log entry does not mean the user connecting, but just the automount map it is looking for.
It appeared I had a misconfiguration on AD.
By raising the domain debug_level to 6 in my sssd.conf as follows:
...
[domain/example.com]
debug_level = 6
...I was able to view the LDAP query made to my AD server.
It appears I had to place my nisObjects under my nisMap's, I had them placed in the same OU=automount.
So I moved these objects and all is working fine now!
|
I am trying to set up SSSD to get automount maps from Active Directory.
I think my settings are correct but it uses the wrong username to query AD.
It takes whatever that is set as "mapname" (behind the + sign) from /etc/auto.master, for example +auto.master results in the following debug log (sssd_autofs debug_level=6):
[sssd[autofs]] [accept_fd_handler] (0x0400): Client connected!
[sssd[autofs]] [sss_cmd_get_version] (0x0200): Received client version [1].
[sssd[autofs]] [sss_cmd_get_version] (0x0200): Offered version [1].
[sssd[autofs]] [sss_autofs_cmd_setautomntent] (0x0400): Got request for automount map named [emailprotected]
[sssd[autofs]] [sss_parse_name_for_domains] (0x0200): name '[emailprotected]' matched expression for domain 'example.com', user is auto.master
[sssd[autofs]] [setautomntent_send] (0x0400): Requesting info for automount map [auto.master] from [example.com]
[sssd[autofs]] [lookup_automntmap_step] (0x0400): Requesting info for [[emailprotected]]
[sssd[autofs]] [sysdb_get_map_byname] (0x0400): No such map
[sssd[autofs]] [lookup_automntmap_step] (0x0080): No automount map [auto.master] in cache for domain [example.com]
[sssd[autofs]] [sss_dp_issue_request] (0x0400): Issuing request for [0x406840:0:[emailprotected]]
[sssd[autofs]] [sss_dp_get_autofs_msg] (0x0400): Creating autofs request for [example.com][4105][mapname=auto.master]
[sssd[autofs]] [sss_dp_internal_get_send] (0x0400): Entering request [0x406840:0:[emailprotected]]
[sssd[autofs]] [lookup_automntmap_step] (0x0400): Requesting info for [[emailprotected]]
[sssd[autofs]] [sysdb_autofs_entries_by_map] (0x0400): Getting entries for map auto.master
[sssd[autofs]] [sysdb_autofs_entries_by_map] (0x0400): No entries for the map
[sssd[autofs]] [lookup_automntmap_step] (0x0400): setautomntent done for map auto.master
[sssd[autofs]] [sss_autofs_cmd_setautomntent_done] (0x0400): setautomntent found data
[sssd[autofs]] [sss_dp_req_destructor] (0x0400): Deleting request: [0x406840:0:[emailprotected]]
[sssd[autofs]] [sss_autofs_cmd_getautomntent] (0x0400): Requested data of map [emailprotected] cursor 0 max entries 512
[sssd[autofs]] [sss_autofs_cmd_getautomntent] (0x0400): Performing implicit setautomntent
[sssd[autofs]] [sss_parse_name_for_domains] (0x0200): name '[emailprotected]' matched expression for domain 'example.com', user is auto.master
[sssd[autofs]] [setautomntent_send] (0x0400): Requesting info for automount map [auto.master] from [example.com]
[sssd[autofs]] [lookup_automntmap_step] (0x0400): Requesting info for [[emailprotected]]
[sssd[autofs]] [sss_dp_issue_request] (0x0400): Issuing request for [0x406840:0:[emailprotected]]
[sssd[autofs]] [sss_dp_get_autofs_msg] (0x0400): Creating autofs request for [example.com][4105][mapname=auto.master]
[sssd[autofs]] [sss_dp_internal_get_send] (0x0400): Entering request [0x406840:0:[emailprotected]]
[sssd[autofs]] [lookup_automntmap_step] (0x0400): Requesting info for [[emailprotected]]
[sssd[autofs]] [sysdb_autofs_entries_by_map] (0x0400): Getting entries for map auto.master
[sssd[autofs]] [sysdb_autofs_entries_by_map] (0x0400): No entries for the map
[sssd[autofs]] [lookup_automntmap_step] (0x0400): setautomntent done for map auto.master
[sssd[autofs]] [getautomntent_implicit_done] (0x0020): Cannot get map after setautomntent succeeded?
[sssd[autofs]] [sss_dp_req_destructor] (0x0400): Deleting request: [0x406840:0:[emailprotected]]
[sssd[autofs]] [sss_autofs_cmd_endautomntent] (0x0400): endautomntent called
[sssd[autofs]] [client_recv] (0x0200): Client disconnected!Anyone got this working?
| SSSD and autofs |
I have resolved this issue. The loginshell Attribute was not accessible due to an access rule from the ldap side.
|
I have configured an LDAP server and created a user. ldapsearch delivers the following results:
# user, People, brave-vesperia.com
dn: uid=masc,ou=People,dc=brave-vesperia,dc=com
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
uid: masc
cn: user user
sn: user
givenName: ###
title: Dr.
telephoneNumber: #####
mobile: #####
postalAddress: #####
userPassword:: e1NTSEF9QzVQNUp5R2h4NkZzVzRuUzlCZWdlcFlwaVVFWEk0Mno=
labeledURI: #####
loginShell: /bin/bash
uidNumber: 9999
gidNumber: 9999
homeDirectory: /home/masc
description: Admin UserI have configured sssd on my client and can now login using my ldap account. However, the shell I'm getting is /bin/sh.
Here's my sssd configuration:
[sssd]
config_file_version = 2
services = nss, pam, sudo
domains = brave-vesperia.com[domain/brave-vesperia.com]
cache_credentials = true
enumerate = trueid_provider = ldap
auth_provider = ldapldap_uri = ldap://ldap.brave-vesperia.com
ldap_search_base = dc=brave-vesperia,dc=com
ldap_id_use_start_tls = true
ldap_tls_reqcert = demand
ldap_tls_cacert = /etc/openldap/certs/ca.pem
chpass_provider = ldap
ldap_chpass_uri = ldap://ldap.brave-vesperia.com
entry_cache_timeout = 600
ldap_network_timeout = 2ldap_schema = rfc2307bis
ldap_group_member = uniqueMemberHere's the output of getent masc passwd
masc:*:1001:1001::/home/masc:/bin/sh is not a symlink to /bin/bash. I have tested both an AlmaLinux and an Ubuntu Client so it's unlikely to be client related.
Searching through the logs I see the following lines repeatedly:
(2022-04-21 5:35:46): [be[brave-vesperia.com]] [sdap_get_map] (0x0400): Option ldap_user_shell has value loginShellsssd_brave-vesperia.com.log:(2022-04-21 6:25:50): [be[brave-vesperia.com]] [sysdb_remove_attrs] (0x2000): Removing attribute [loginShell] from [[emailprotected]] | sssd doesn't query LDAP for loginshell |
Interesting, order does matter in PAM. It works if pam_unix come before pam_sss:
auth sufficient pam_unix.so try_first_pass nullok
auth sufficient pam_sss.so use_first_passpassword sufficient pam_unix.so try_first_pass use_authtok nullok sha512 shadow
password sufficient pam_sss.so use_authtok |
I'm trying to setup sudo-ldap in a clean CentOS 7 docker environment. I've successfully setup sssd and PAM authentication, and it works.
However, sudo-ldap works only if !authenticate is set:
dn: cn=test,ou=SUDOers,ou=People,dc=srv,dc=world
objectClass: top
objectClass: sudoRole
cn: test
sudoUser: test
sudoHost: ALL
sudoRunAsUser: ALL
sudoCommand: ALL
sudoCommand: !/bin/cp
sudoOption: !authenticateWhen I run sudo cp, I got the following debug logs:
# without !authenticate
sudo: searching LDAP for sudoers entries
sudo: ldap sudoRunAsUser 'ALL' ... MATCH!
sudo: ldap sudoCommand 'ALL' ... MATCH!
sudo: ldap sudoCommand '!/bin/cp' ... MATCH!
sudo: Command allowed
sudo: LDAP entry: 0x55ed4d71b930
sudo: done with LDAP searches
sudo: user_matches=true
sudo: host_matches=true
sudo: sudo_ldap_lookup(0)=0x02[sudo] password for test:
Sorry, try again.# with !authenticate
sudo: searching LDAP for sudoers entries
sudo: ldap sudoRunAsUser 'ALL' ... MATCH!
sudo: ldap sudoCommand 'ALL' ... MATCH!
sudo: Command allowed
sudo: LDAP entry: 0x564d56cb9960
sudo: done with LDAP searches
sudo: user_matches=true
sudo: host_matches=true
sudo: sudo_ldap_lookup(0)=0x02
sudo: removing reusable search result
cp: missing file operand
Try 'cp --help' for more information.I can use the password to login via SSH, but not able to run sudo command, does anyone know what's wrong?
Attached /etc/pam.d/system-auth (sudo is including that file)
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth required pam_env.so
auth sufficient pam_sss.so use_first_pass
auth sufficient pam_unix.so try_first_pass nullok
auth required pam_deny.soaccount required pam_unix.sopassword requisite pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password sufficient pam_sss.so use_authtok
password sufficient pam_unix.so try_first_pass use_authtok nullok sha512 shadow
password required pam_deny.sosession optional pam_keyinit.so revoke
session required pam_limits.so
-session optional pam_systemd.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required pam_unix.so
session optional pam_sss.so
session required pam_mkhomedir.so skel=/etc/skel umask=0022 | sudo-ldap works with !authenticate only |
nsswitch config file define the availability and order of querying name services (for hosts, users, groups, etc)
sssd manage access to remote directories and authentication mechanisms. It is extensively use to for authentication from AD
nslcd do LDAP queries for local processes based on a simple configuration file.
Generally speaking they do not have much in common.
|
I'm trying to configure sssd instead of nslcd for my Rhel system, and then I came across nsswitch.
What's the difference between these three?
| Difference between nsswitch, nslcd and sssd? |
Have a look into Anatomy of SSSD user lookup for an overview of the lookup process or Troubleshooting Guide for how to get logs to see what might be wrong in the daemon.
For quick reference, you may need to add debug_level=10 into all sections in the sssd.conf file, restart sssd and re-run your tasks. Then look into /var/log/sssd*.
|
I'm stuck with Kerberos - sssd - AD. I've tried a lot of things, with lot of googling, in LinuxMint, Ubuntu 16.04 and Debian 9. I have always the same result :kinit username works fine
msktutil -u --computer-name $(hostname) --server ad-server.univ-fr looks good
ldapsearch -Y GSSAPI works finebut getent passwd -s sss username does nothing nor id username!
I tried with a very minimalistic Debian 9 distribution with openssh-server, krb-5-user, msktutil, sssd and configuration files /etc/sssd/sssd.conf and /etc/krb5.conf. I did not change /etc/nsswitch as it seems to be right configuring with compact sss on passwd, group, shadow and gshadow.
It looks like that sss is never called. So I did not find any log that could help me to track the bug. I don't know if I miss a package or something else.
My question : How could I find out how nsswitch works and when it ask sssd to find a AD username?
| How nsswitch call sssd for credential? |
Turns out it was something unrelated - DOH.
It was running a custom bash script for ssh AuthorizedKeysCommand to fetch keys from an LDAP attribute. It was writing a cached version of the key to the user's home directory, and creating the path if it didn't exist.
This, it turns out, was causing the pam_mkhomedir never to run, because the directory was already there, at least if I was using key based authentication. As such, it wasn't a problem with pam mkdir at all.
Once I removed this script, it worked perfectly. I've now rewritten the script to store the ssh key cache outside the home directory, and everything working exactly as expected.
Just documenting it here as a reminder to anyone else who may be similarly stuck - think outside the box, and ensure that pam_mkhomedir is actually running when it should, especially when custom scripting is in play.
|
Currently, I have a fleet of linux computers joined to an active directory domain with SSSD for user management - primarily ubuntu, with some Raspian as well.
I'm using pam_mkhomedir.so to create home directories locally for any domain login, via /etc/pam.d/common-session.
session required pam_mkhomedir.so skel=/etc/skel/ umask=0077This works great for local console login, as well as su [domainuser]. It creates the directory in /home/[domain]/[user]. However, when the user's first login is via SSH (which is usually the case for servers), it causes the directory to be owned by root:root, instead of the correct user.
I've been tearing my hair out with this one, trying anything I can find. Any ideas?
| Domain Joined Linux - PAM mkhomedir creating homedirs owned as root for SSH |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.