1

I know that I need to escape the @cmd var to run:

declare @cmd 'xp_cmdshell ''echo Mary|Warrior > c:\test.txt'''
exec (@cmd)

because the character '|' would fail when running the command.

So, previous running I set:

set @cmd = replace(@cmd, '|', '^|')

As @cmd var could be any string (sent by users)... What other characters do I need to worry about ?

(I know a couple of them such as >, <)

user3770963
  • 47
  • 1
  • 7
  • 2
    Why are you executing a string value that you receive from your users? This is a potential sql injection vulnerability. – Sean Lange Sep 23 '16 at 18:43

2 Answers2

1

Use ^ to escape the special character.

declare @cmd varchar(max) = N'echo Mary^|Warrior > C:\test1.txt'
exec master.sys.xp_cmdshell @cmd

OR

declare @cmd1 varchar(max) = N'xp_cmdshell ''echo Mary^|Warrior > C:\test11.txt'''
exec (@cmd1)
p2k
  • 2,126
  • 4
  • 23
  • 39
0

You can try using this query, As sean mentioned it is potential sql injection

declare @cmd nvarchar(500) = N'echo ''Mary|Warrior'' > c:\test.txt'
exec master.sys.xp_cmdshell @cmd
Kannan Kandasamy
  • 13,405
  • 3
  • 25
  • 38